golang: declaring a camelcase in a struct declaration - go

I'm trying to read a yaml file via golang.
But the "matchLabels" sub-struct is not being recognized
yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: nginx-deploy
labels:
app: test
spec:
replicas: 3
selector:
matchLabels:
app: web
struct
type myData struct {
Apivesion string `yaml:"apiVersion"`
Kind string
Metadata struct {
Name string
Labels struct {
App string
}
}
Spec struct {
Replicas int64
Selector struct {
Matchlabels struct {
App string
}
}
}
}
Expectation
&{apps/v1 Deployment {nginx-deploy {test}} {3 {{web}}}}
Result
&{apps/v1 Deployment {nginx-deploy {test}} {3 {{}}}}
Fix didn't work:
Matchlabels struct `yaml:"matchLabels"` {

Cerise Limón gave the answer in a comment:
Field tags follow the type:
Matchlabels struct { App string }
`yaml:"matchLabels"`

I don't think you implemented the suggested answer correctly, see where the tag is:
type myData struct {
Apivesion string `yaml:"apiVersion"`
Kind string
Metadata struct {
Name string
Labels struct {
App string
}
}
Spec struct {
Replicas int64
Selector struct {
Matchlabels struct {
App string
} `yaml:"matchLabels"`
}
}
}
See also: https://go.dev/play/p/yd9c-iBz2yL

type AutoGenerated struct {
APIVersion string `yaml:"apiVersion"`
Kind string `yaml:"kind"`
Metadata struct {
Name string `yaml:"name"`
Labels struct {
App string `yaml:"app"`
} `yaml:"labels"`
} `yaml:"metadata"`
Spec struct {
Replicas int `yaml:"replicas"`
Selector struct {
MatchLabels struct {
App string `yaml:"app"`
} `yaml:"matchLabels"`
} `yaml:"selector"`
} `yaml:"spec"`
}
You can use this tool, it is really helpful:
https://zhwt.github.io/yaml-to-go/

Related

Go Testing define custom structure

I've followed the structure in a tf file, can you help me to create a proper structure, as I'm new to Go.
Here is tf
ipv4 = {
cidrblock = "10.0.0.0/16"
secondary = [
{
cidrs = "20.0.0.0/16"
enabled = true
},
{
cidrs = "30.0.0.0/16"
enabled = true
}
]
}
So I've an object of strings, as well a list of objects in the main object. I could make a primitive type, for example:
type ipv4 struct {
cidrblock string
cidrs string
enabled bool
}
type ipv6 struct {
border string
generate bool
}
type Sets struct {
Name string
IPv4 *ipv4
IPv6 *ipv6
Tags map[string]string
Tenancy string
}
But I would really like to have a complex structure
you can do something like this:
type ipv4 struct {
cidrblock string
secondary []ipv4secondary
}
type ipv4secondary struct {
cidrblock string
enabled bool
}
and use it as this:
example := ipv4{
cidrblock: "10.0.0.0/16",
secondary: []ipv4secondary{
ipv4secondary{cidrblock: "20.0.0.0/16", enabled: true},
ipv4secondary{cidrblock: "30.0.0.0/16", enabled: true},
},
}
here is the example: https://go.dev/play/p/U7o0BbAis9T

Populate a struct with an array of sub-structs to turn into json

I’m trying to post some JSON. Using the JSON-to-Go tool I have this struct defined:
type IssueSetState struct {
ID string `json:"id"`
CustomFields []struct {
Value struct {
Name string `json:"name"`
} `json:"value"`
Name string `json:"name"`
Type string `json:"$type"`
} `json:"customFields"`
}
I’m trying to populate it with some data that I can then pass into the http library:
jsonValues := &IssueSetState{
ID: resultEntityId.ID,
CustomFields: []{
Value: {
Name: "Fixed",
},
Name: "State",
Type: "StateIssueCustomField",
},
}
jsonEncoded := new(bytes.Buffer)
json.NewEncoder(jsonEncoded).Encode(jsonValues)
I keep getting errors like:
./main.go:245:19: syntax error: unexpected {, expecting type
./main.go:246:9: syntax error: unexpected :, expecting comma or }
./main.go:249:8: syntax error: unexpected : at end of statement
./main.go:251:4: syntax error: unexpected comma after top level declaration
I’m sure the mistake I’m making is a simple one, but I’m new to Go.
One possible way is to define named structs for every anonymous struct you have.
type IssueSetState struct {
ID string `json:"id"`
CustomFields []CustomField `json:"customFields"`
}
type CustomField struct {
Value Value `json:"value"`
Name string `json:"name"`
Type string `json:"type"`
}
type Value struct {
Name string `json:"name"`
}
Now you can create it like this:
IssueSetState{
ID: resultEntityId.ID,
CustomFields: []CustomField{
{
Value: Value{
Name: "Fixed",
},
Name: "State",
Type: "StateIssueCustomField",
},
{
Value: Value{
Name: "Fixed",
},
Name: "State",
Type: "StateIssueCustomField",
},
},
}
So you're initializing the jsonValue badly.
You can fix it in 2 ways:
https://play.golang.org/p/LFO4tOLyG60
making structures flat
https://play.golang.org/p/TyFfaMf7XeF
by repeating the structure definition when declaring value
The first one should be easier and clearer.

Golang - Missing expression error on structs

type Old struct {
UserID int `json:"user_ID"`
Data struct {
Address string `json:"address"`
} `json:"old_data"`
}
type New struct {
UserID int `json:"userId"`
Data struct {
Address string `json:"address"`
} `json:"new_data"`
}
func (old Old) ToNew() New {
return New{
UserID: old.UserID,
Data: { // from here it says missing expression
Address: old.Data.Address,
},
}
}
What is "missing expression" error when using structs?
I am transforming old object to a new one. I minified them just to get straight to the point but the transformation is much more complex. The UserID field for example works great. But when I use struct (which intended to be a JSON object in the end) the Goland IDE screams "missing expression" and the compiler says "missing type in composite literal" on this line. What I am doing wrong? Maybe should I use something else instead of struct? Please help.
Data is an anonymous struct, so you need to write it like this:
type New struct {
UserID int `json:"userId"`
Data struct {
Address string `json:"address"`
} `json:"new_data"`
}
func (old Old) ToNew() New {
return New{
UserID: old.UserID,
Data: struct {
Address string `json:"address"`
}{
Address: old.Data.Address,
},
}
}
(playground link)
I think it'd be cleanest to create a named Address struct.
You're defining Data as an inline struct. When assigning values to it, you must first put the inline declaration:
func (old Old) ToNew() New {
return New{
UserID: old.UserID,
Data: struct {
Address string `json:"address"`
}{
Address: old.Data.Address,
},
}
}
Hence it is generally better to define a separate type for Data, just like User.

Instantiation of complex struct

I created a struct in a file called availability.go
package restconsume
import (
)
// Availabilityrequest for sabre
type Availabilityrequest struct {
OTAAirLowFareSearchRQ struct {
OriginDestinationInformation []struct {
DepartureDateTime string `json:"DepartureDateTime"`
DestinationLocation struct {
LocationCode string `json:"LocationCode"`
} `json:"DestinationLocation"`
OriginLocation struct {
LocationCode string `json:"LocationCode"`
} `json:"OriginLocation"`
RPH string `json:"RPH"`
} `json:"OriginDestinationInformation"`
POS struct {
Source []struct {
PseudoCityCode string `json:"PseudoCityCode" default:"F9CE"`
RequestorID struct {
CompanyName struct {
Code string `json:"Code" default:"TN"`
} `json:"CompanyName"`
ID string `json:"ID" default:"1"`
Type string `json:"Type" default:"1"`
} `json:"RequestorID"`
} `json:"Source"`
} `json:"POS"`
TPAExtensions struct {
IntelliSellTransaction struct {
RequestType struct {
Name string `json:"Name" default:"200ITINS"`
} `json:"RequestType"`
} `json:"IntelliSellTransaction"`
} `json:"TPA_Extensions"`
TravelPreferences struct {
TPAExtensions struct {
DataSources struct {
ATPCO string `json:"ATPCO" default:"Enable"`
LCC string `json:"LCC" default:"Disable"`
NDC string `json:"NDC" default:"Disable"`
} `json:"DataSources"`
NumTrips struct {
} `json:"NumTrips"`
} `json:"TPA_Extensions"`
} `json:"TravelPreferences"`
TravelerInfoSummary struct {
AirTravelerAvail []struct {
PassengerTypeQuantity []struct {
Code string `json:"Code"`
Quantity int `json:"Quantity"`
} `json:"PassengerTypeQuantity"`
} `json:"AirTravelerAvail"`
SeatsRequested []int `json:"SeatsRequested" default:"1"`
} `json:"TravelerInfoSummary"`
Version string `json:"Version" default:"1"`
} `json:"OTA_AirLowFareSearchRQ"`
}
// AddADepartureDate to set the date you leave
func (a *Availabilityrequest) AddADepartureDate() Availabilityrequest {
a.OTAAirLowFareSearchRQ.OriginDestinationInformation[0].DepartureDateTime = "2020-03-21"
return *a
}
//AddOriginDestination to set the ori and dest
func (a *Availabilityrequest) AddOriginDestination(Origin ,Destination string) {
a.OTAAirLowFareSearchRQ.OriginDestinationInformation[0].DestinationLocation.LocationCode = Destination
a.OTAAirLowFareSearchRQ.OriginDestinationInformation[0].OriginLocation.LocationCode = Origin
}
Now I've imported this package into my main one and having issue instatntiating with only one substruct(TPAExtensions)
main.go
package main
import (
"restconsume"
"fmt"
)
func main() {
var a= new(restconsume.Availabilityrequest)
a = Availabilityrequest{
"OTA_AirLowFareSearchRQ":OTAAirLowFareSearchRQ{
"IntelliSellTransaction": IntelliSellTransaction{
"RequestType": RequestType{
"Name": "200ITINS"},
},
},
}
}
error message
undefined: Availabilityrequest
My question is how could I instantiate this kind of complex struct?
The simplest answer is to not try to use struct literal but rather have a variable of the top-level type to be initialized to an appropriate zero value for its type and then explicitly set only those fields which are needed, like this:
var a Availabilityrequest
a.OTAAirLowFareSearchRQ.TPAExtensions.IntelliSellTransaction.RequestType.Name = "200ITINS"
But honestly, judging from your question, it looks like you're JavaScript programmer trying to attack Go without much prior knowledge about that language. This is a path to suffering.
Please be advised to at least start with the Tour of Go and then read any introductory-level book on Go (I would recommend this one).
"Effective Go" is also a must.

Go create struct from XML

Please see this playground: https://play.golang.org/p/FOMWqhjdneg
As you can see I have a XML response which I want to unmarshal into a Product struct. The XML has an "assetBlock" which contains nested nodes and extract data to Product struct. Any help would be appreciated
You need to make a struct for AssetBlock and all of the types below it, I've done it up to group to show you what I mean:
https://play.golang.org/p/vj_CkneHuLd
type Product struct {
GlobalID string `xml:"globalId"`
Title string `xml:"title"`
ChunkID int `xml:"gpcChunkId"`
AssetBlock assetBlock `xml:"assetBlock"`
}
type assetBlock struct {
Images images `xml:"images"`
}
type images struct {
GroupList groupList `xml:"groupList"`
}
type groupList struct {
Groups []group `xml:"group"`
}
type group struct {
Usage string `xml:"usage"`
Size string `xml:"size"`
}

Resources