It is possible, using Terratest, to declare a tfvars file with the following variable:
bar = {
name = "test"
domain = "test.com"
regions = [
{ location = "France Central", alias = "france" }
]
}
But include a random prefix to the bar.domain string inside the go code?
I'm using terraformOptions as follows:
terraformOptions := &terraform.Options{
TerraformDir: sourcePath,
VarFiles: []string{variablesPath + "/integration.tfvars"},
}
It is not ideal for one to make use of the tfvars file directly to take the input in case of tests. More on this here
To answer your question :
You can use something similar to this :
options := terraform.Options{
TerraformDir: "sourcePath",
Vars: map[string]interface{}{
"name": "test",
"domain": addRandomprefix()+"test.com",
"region ": map[string]interface{}{
"location" : "France Central",
"alias" : "france",
},
},
}
Just create your own custom addRandomprefix() method. I hope this helps :)
Related
I need help for transforming this input map into the output map. I try with switch/case and for but I didn't succeed it. Thanks a lot !
Input :
Values{
"toto_voiture_brand": Ad{
"CITROEN": "CITROEN",
},
"toto_voiture_model": Ad{
"CITROEN_toto": "C3",
},
"toto_moto_brand": Ad{
"KAWASAKI": "KAWASAKI",
},
"toto_moto_model": Ad{
"KAWASAKI_tata": "Ninja 1000 SX",
},
"toto_camion_brand": Ad{
"RENAULT": "RENAULT",
"PEUGEOT": "PEUGEOT",
},
"toto_camion_model": Ad{
"RENAULT_toto": "J5",
"PEUGEOT_tata": "255",
},
},
}
Output
Values{
"toto_voiture_model": {
"Citroen": {
{Value: "C3"},
},
},
"toto_moto_model": {
"Kawasaki": {
{Value: "Ninja 1000 SX"},
},
},
"toto_camion_model": {
"RENAULT": {
{Value: "J5"},
},
"PEUGEOT": {
{Value: "255"},
},
},
}
I've tried with switch case and loop for and map. But I don't have the result attendee, I didn't found how to match every map, key and value. Thanks a lot
I should have managed what you need with the following code:
package main
import (
"encoding/json"
"fmt"
"strings"
)
type Output struct {
Value string `json:"Value"`
}
func main() {
// declare output
output := make(map[string]map[string]Output, 0)
// input
input := make(map[string]map[string]string, 0)
input["toto_voiture_brand"] = map[string]string{
"CITROEN": "CITROEN",
}
input["toto_voiture_model"] = map[string]string{
"CITROEN_toto": "C3",
}
input["toto_moto_model"] = map[string]string{
"KAWASAKI_tata": "Ninja 1000 SX",
}
input["toto_camion_model"] = map[string]string{
"RENAULT_toto": "J5",
"PEUGEOT_tata": "255",
}
// transformation
for k, v := range input {
if strings.HasSuffix(k, "_model") {
tempMap := make(map[string]Output, len(v))
for kk, vv := range v {
key := strings.Split(kk, "_")[0]
tempMap[key] = Output{
Value: vv,
}
}
output[k] = tempMap
}
}
data, _ := json.MarshalIndent(&output, "", "\t")
fmt.Println(string(data))
}
I put some comments within the code just to separate sections. The first two parts are only supposed to define your input and output variables.
The section starting with // transformation is a good candidate to become a function but I preferred to leave it within the main function for demo purposes. Let me recap what's happens in the loop:
You range over the entries of your input variable
If the key has the suffix _model, you take it into consideration
You define a locally-scoped map (called tempMap) of type map[string]Output with the right number of elements that we're gonna add
You range over the v variable (that's why we're dealing with nested maps)
For each item, you're gonna add an entry to the tempMap
At the end of the nested loop, you add an entry to the parent map (output)
The last part is only for printing a beautiful JSON that can be easily read and checked.
Note that this code is simplified just to show off how to achieve your goal, adjust it before putting it into production.
Let me know if this helps, thanks!
I am working on unit test for a restAPI implementation in Golang.
I need to pass an array of object into url.
Here is an example of struct I have:
type version struct {
Name string `json:"name"`
Ver string `json:"ver"`
}
type event struct {
ID string `json:"id"`
Title string `json:"Title"`
Description string `json:"Description"`
Versions []version `json:"versions"`
}
The sample json input i tested in postman will be look like this one
{
"id": "101",
"title": "This is simple Golang title for testing!",
"Description":"Sample code for REST api implementation in Golang 2021!",
"versions": [
{
"name": "pingPong",
"ver": "10.2"
},
{
"name": "Ninja",
"ver": "10.24"
}
]
}
My question is that how can i pass an array of objects as URL parameters.
I expect to have something like below but not how to fill the ending part i highlighted by the ...
url?ID=20&Title=urlTitle&Description=UrlDescription&...
I don't know how you want the URL like, so I wrote it myself in a way that you can change it any way you want, And let me add that I don't know how many versions you have, so I wrote in such a way that no matter how many versions you have, it can handle it.
package main
import (
"fmt"
"strings"
"encoding/json"
)
var jsonData string =
`{
"id": "101",
"title": "This is simple Golang title for testing!",
"Description":"Sample code for REST api implementation in Golang 2021!",
"versions": [
{
"name": "pingPong",
"ver": "10.2"
},
{
"name": "Ninja",
"ver": "10.24"
}
]
}`
type (
Event struct {
Id string `json:"id"`
Title string `json:"title"`
Description string `json:"description"`
Versions []Version `json:"versions"`
}
Version struct {
Name string `json:"name"`
Ver string `json:"ver"`
}
)
func fillVersions(event *Event, baseUrl string) string {
var finalUrl string = baseUrl
for index, value := range event.Versions {
restUrl := fmt.Sprintf("Version%d=%s-%s", index + 1, value.Name, value.Ver)
finalUrl = fmt.Sprintf(
finalUrl + "%s" + "&",
restUrl,
)
}
return strings.TrimRight(finalUrl, "&")
}
func main() {
var event Event
json.Unmarshal([]byte(jsonData), &event)
baseUrl := fmt.Sprintf(
"https://test.com/test?Id=%s&Title=%s&Description=%s&",
event.Id,
event.Title,
event.Description,
)
finalUrl := fillVersions(&event, baseUrl)
fmt.Println(finalUrl)
}
The output of the program is as follows:
https://test.com/test?Id=101&Title=This is simple Golang title for testing!&Description=Sample code for REST api implementation in Golang 2021!&Version1=pingPong-10.2&Version2=Ninja-10.24
I would also like to say that the last & will be removed, If you don't want to do this, Remove the following line and write as follows (also remove the strings library from the import scope):
return strings.TrimRight(finalUrl, "&") // remove this
return finalUrl // add this
I have some entities in my database called "events". Each of these events contain an array of string, called "tags".
I want to make a query to get all the events matching an array of tags that I will give in parameter.
BUT, I want these events to be sorted like:
The first one is the one containing most of the tags I give in parameter.
The second one is the second one containing most of the tags I give in parameter.
And so on.
If there are more than one event containing the same amount of tags I want them to be sorted by their "name" property in alphabetical order.
Example:
"name" = "event1", "tags" = ["food", "music", "gaming", "sport"]
"name" = "event2", "tags" = ["gaming"]
"name" = "event3", "tags" = ["music", "sport"]
"name" = "event4", "tags" = ["food", "music", "gaming", "sport"]
"name" = "event5", "tags" = ["music", "sport", "coding"]
"name" = "event6", "tags" = ["coding"]
"name" = "event7", "tags" = ["food", "gaming", "sport"]
The array of tags that I give in parameter for this example is: ["food", "music", "gaming", "sport"]
The result for this example will be an array of events, containing in that order:
event1, event4, event7, event3, event5, event2
To get all the events containing the tags I simply make a query with the "$or" operators. This allowed me to get all the events if they contained at least one of the tag given in parameter.
Code:
var events []model.Event
var MyQuery []map[string]interface{}
for i := 0; i < len(tags); i++ {
currentCondition := bson.M{"tags": tags[i]}
MyQuery = append(MyQuery, currentCondition)
}
err := dbEvents.C(collectionEvents).Find(bson.M{"$or": OrQuery}).All(&events)
But i really don't know how to sort them like I showed you.
package main
import (
"fmt"
"github.com/ahmetb/go-linq"
)
type T struct {
Name string
Tags []string
}
func main() {
params := []string{"food", "music", "gaming", "sport"}
t := []T{
T{Name: "event1", Tags: []string{"food", "music", "gaming", "sport"}},
T{Name: "event2", Tags: []string{"gaming"}},
T{Name: "event3", Tags: []string{"music", "sport"}},
T{Name: "event4", Tags: []string{"food", "music", "gaming", "sport"}},
T{Name: "event5", Tags: []string{"music", "coding", "sport"}},
T{Name: "event6", Tags: []string{"coding"}},
T{Name: "event7", Tags: []string{"food", "gaming", "sport"}},
}
var result []T
linq.From(t).SortT(func(t1 T, t2 T) bool {
var rs1 []string
linq.From(t1.Tags).IntersectByT(linq.From(params), func(str string) string {
return str
}).ToSlice(&rs1)
var rs2 []string
linq.From(t2.Tags).IntersectByT(linq.From(params), func(str string) string {
return str
}).ToSlice(&rs2)
return len(rs1) > len(rs2)
}).ToSlice(&result)
fmt.Printf("%+v", result)
}
[{Name:event1 Tags:[food music gaming sport]} {Name:event4 Tags:[food music gaming sport]} {Name:event7 Tags:[food gaming sport]} {Name:event3 Tags:[music sport]} {Name:event5 Tags:[music coding sport]} {Name:event2 Tags:[gaming]} {Name:event6 Tags:[coding]}]
Above program sorts the array as per your requirements, Hope this will help you.
I want to do a multi-level array element delete. My Structs are as follows:-
type Company struct {
Id bson.ObjectId `bson:"_id,omitempty"`
CompanyName string
Process []ProcessItem
}
type ProcessItem struct{
SortOrder int
Documents []DocumentTemplate
}
type DocumentTemplate struct {
Id bson.ObjectId `bson:"_id,omitempty"`
TemplateName string
}
I want to delete an object of type DocumentTemplate. The DocumentTemplate is a struct array in ProcessItem which is a struct array in Company struct. I have Company Id(field of struct Company) and TemplateName(field of struct DocumentTemplate).
I tried the below mgo pull query but it is not working.
c := db.C("company")
pullQuery := bson.M{"process": bson.M{"documents.templatename": "xyz"}}
err := c.Update(bson.M{"_id": "123"}, bson.M{"$pull": pullQuery})
Please point out the mistakes I made here. Thanks.
Edit:
Adding one example document for the clarity of the question
{
"_id" : ObjectId("573da7dddd73171e42a84045"),
"companyname" : "AAA",
"process" : [
{
"processname" : "Enquiry",
"sortorder" : 0,
"documents" : [
{
"templatename" : "xyz",
"processname" : "Enquiry"
},
{
"templatename" : "ss",
"processname" : "Enquiry"
}
]
},
{
"processname" : "Converted",
"processtype" : 1,
"sortorder" : 2,
"documents" : [
{
"templatename" : "dd",
"processname" : "Converted"
},
{
"templatename" : "fg",
"processname" : "Converted"
}
]
}
]
}
I need to pull out just one DocumentTemplete record, like the one below:
{
"templatename" : "xyz",
"processname" : "Enquiry"
}
N.B: TemplateName will be unique inside a Company.
You'll need to use the $ positional operator (https://docs.mongodb.com/manual/reference/operator/projection/positional/). In order to be able to use that you'll also have to add to your query the following:
"process.documents.templatename": "xyz"
Your Update statement should look like this:
c := db.C("company")
pullQuery := bson.M{"process.$.documents": bson.M{"templatename": "xyz"}}
err := c.Update(bson.M{"_id": "123", "process.documents.templatename": "xyz"}, bson.M{"$pull": pullQuery})
You can pull values in array from the array in mongo record
change2 := bson.M{
"$pull": bson.M{"sapinfo.systemstatus": bson.M{"$in": tags}},
}
How do you quickly find the URL for a Win32 API on MSDN? It's easy for .NET methods -- just add the method name (for example, System.Byte.ToString) to http://msdn.microsoft.com/library/.
However, for Win32 APIs (say GetLongPathName), this doesn't work: http://msdn.microsoft.com/en-us/library/GetLongPathName.
I want to be able to use the URL in code comments or documentation. So the URL one gets with an MSDN or Google search (for example, http://msdn.microsoft.com/library/aa364980.aspx) isn't really what I'm looking for. I'd really like my code comments to look something like:
// blah blah blah. See http://msdn.microsoft.com/en-us/library/GetLongPathName for more information.
What's the magic pixie dust for Win32 APIs? Or does it only work for .NET methods?
Google might be your best bet. I know the msdn site search has time and again pointed me in the wrong direction, but a quick switch to Google ("GetLongPathName site:msdn.microsoft.com") never steers me wrong.
FWIW if you have the MSDN installed locally on your machine the Zeus editor has a feature to search the local copy of the MSDN.
For example, placing the cursor on the GetLongPathName word within a text document and using the Zeus Help, Quick Help, Current Word menu, the following MSDN page gets loaded:
ms-help://MS.VSCC.v80/MS.MSDN.vAug06.en/fileio/fs/getlongpathname.htm
I am using Linkify by cough me, which lets you link
// see msdn:GetLongPathName
to the google search japollock mentions.
You could use MSDN search.
http://social.msdn.microsoft.com/Search/en-US/?Refinement=86&Query=GetLongPathName
Refinement=86 stands for Win32 search.
MSDN GET api (I don't know how new this is)
"https://learn.microsoft.com/api/search?locale=en-us&scoringprofile=semantic-captions&%24top=1&search=" functionName
returns json like such:
{
"results": [
{
"title": "KeClearEvent function (wdm.h) - Windows drivers",
"url": "https://learn.microsoft.com/en-us/windows-hardware/drivers/ddi/wdm/nf-wdm-keclearevent",
"displayUrl": {
"content": "/windows-hardware/drivers/ddi/wdm/nf-wdm-keclearevent",
"hitHighlights": [
{
"start": 41,
"length": 12
}
]
},
"description": "The KeClearEvent routine sets an event to a not-signaled state.",
"descriptions": [
{
"content": "KeClearEvent function (wdm.h) Article 04/18/2022 2 minutes to read In this article The KeClearEvent routine sets an event to a not-signaled state.",
"hitHighlights": [
{
"start": 0,
"length": 12
},
{
"start": 87,
"length": 12
}
]
},
{
"content": "For better performance, use KeClearEvent unless the caller uses the value returned by KeResetEvent to determine what to do next.",
"hitHighlights": [
{
"start": 28,
"length": 12
}
]
}
],
"lastUpdatedDate": "2022-04-18T04:31:00+00:00",
"breadcrumbs": []
}
],
"spellingCorrection": [],
"scopeRemoved": false,
"count": 18,
"nextLink": "https://learn.microsoft.com/api/Search?locale=en-us\u0026search=KeClearEvent\u0026$skip=1\u0026$top=1",
"srcheng": "02"
}
if you want really fast, you can bind it to a hotkey
AutohotkeyV2
#SingleInstance force
ListLines 0
KeyHistory 0
SendMode "Input" ; Recommended for new scripts due to its superior speed and reliability.
SetWorkingDir A_ScriptDir ; Ensures a consistent starting directory.
linkFromName(functionName) {
json:=downloadToVar("https://learn.microsoft.com/api/search?locale=en-us&scoringprofile=semantic-captions&%24top=1&search=" functionName)
obj:=JSON_parse(json)
if (obj.results.Length) {
RegExMatch(obj.results[1].title, ".*?(?=\s|$)", &OutputVar)
if (OutputVar.0 = functionName) {
validUrl:=obj.results[1].url
} else if (OutputVar.0 = functionName "W" || OutputVar.0 = functionName "A") {
validUrl:=SubStr(obj.results[1].url, 1, -1) "w"
}
; A_Clipboard:=validUrl
Run validUrl
}
}
; linkFromName("GetLongPathNameW") ;works
; linkFromName("GetLongPathName") ;works
linkFromName(A_Clipboard)
Exitapp
f3::Exitapp
downloadToVar(url) {
whr := ComObject("WinHttp.WinHttpRequest.5.1")
whr.Open("GET", url, true)
whr.SetRequestHeader("User-Agent", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)")
whr.Send()
; Using 'true' above and the call below allows the script to remain responsive.
whr.WaitForResponse()
return whr.ResponseText
}
JSON_parse(str) {
c_:=1
return JSON_value()
JSON_value() {
char_:=SubStr(str, c_, 1)
Switch char_ {
case "{":
obj_:=Map()
;object
c_++
loop {
skip_s()
if (SubStr(str, c_, 1) == "}") {
c_++
return obj_
}
; key_:=JSON_objKey()
; a or "a"
if (SubStr(str, c_, 1) == "`"") {
RegExMatch(str, "(?:\\.|.)*?(?=`")", &OutputVar, c_ + 1)
key_:=RegExReplace(OutputVar.0, "\\(.)", "$1")
c_+=OutputVar.Len
} else {
RegExMatch(str, ".*?(?=[\s:])", &OutputVar, c_)
key_:=OutputVar.0
c_+=OutputVar.Len
}
c_:=InStr(str, ":", true, c_) + 1
skip_s()
value_:=JSON_value()
obj_[key_]:=value_
obj_.DefineProp(key_, {Value: value_})
skip_s()
if (SubStr(str, c_, 1) == ",") {
c_++, skip_s()
}
}
case "[":
arr_:=[]
;array
c_++
loop {
skip_s()
if (SubStr(str, c_, 1) == "]") {
c_++
return arr_
}
value_:=JSON_value()
arr_.Push(value_)
skip_s()
char_:=SubStr(str, c_, 1)
if (char_ == ",") {
c_++, skip_s()
}
}
case "`"":
RegExMatch(str, "(?:\\.|.)*?(?=`")", &OutputVar, c_ + 1)
unquoted:=RegExReplace(OutputVar.0, "\\(.)", "$1")
c_+=OutputVar.Len + 2
return unquoted
case "0", "1", "2", "3", "4", "5", "6", "7", "8", "9":
RegExMatch(str, "[0-9.]*", &OutputVar, c_)
c_+=OutputVar.Len
return Number(OutputVar.0)
case "t":
;"true"
c_+=4
return {a:1}
case "f":
;"false"
c_+=5
return {a:0}
case "n":
;"null"
c_+=4
return {a:-1}
}
}
skip_s() {
RegExMatch(str, "\s*", &OutputVar, c_)
c_+=OutputVar.Len
}
}