Below is the actual struct type in aws go sdk elbv2 package. There are other parameters in this struct. I have kept only the necessary ones for simplicity.
type CreateTargetGroupInput struct {
_ struct{} `type:"structure"`
Name *string `type:"string" required:"true"`
Port *int64 `min:"1" type:"integer" required:"true"`
Protocol *string `type:"string" required:"true" enum:"ProtocolEnum"`
VpcId *string `type:"string" required:"true"`
}
I need to decode a JSON string with integer number like:
{ "name": "test-tg", "port": "8080", "protocol": "HTTP" ,"vpcId": "vpc-xxxxxx"}
go code:
func main() {
s := `{ "name": "test-tg", "port": "8080", "protocol": "HTTP" ,"vpcId": "vpc-xxxxxx"}`
targetGroupInput := &elbv2.CreateTargetGroupInput{}
err := json.Unmarshal([]byte(s), targetGroupInput)
if err == nil {
fmt.Printf("%+v
", targetGroupInput)
}
}
I'm getting the below output, (if I pass port in integer format it'll work)
{
Name: "testTG",
Port: 0,
Protocol: "HTTP",
VpcId: "vpc-0f2c8a76"
}
My question is there is no json field in the original struct, so whatever valid name I pass as json field, it is still maaping to go field. i.e. I can send Name field as
"name, Name, NamE, etc"
in json and it still works.
I'm confused here. For other user defined struct it wont map properly if I don't provide valid json name as defined against that go field.
Also how do I convert Port to integer from string during Json Unmarshlling?
As of now I'm using the exact copy of the struct in my project and removing the string type to integer for all integer type fields (also removed all pointers from all struct fields) and receiving the json object and I'm then converting it to integer and making the object of original struct.
It takes more time for me to maintain the exact copy by doing some changes in my project folder and to do validation against all such parameters.
I have the following questions.
- Is there a way to convert string to integer during unmarshlling without adding json tag like (
json:",string"
) against the integer field. - Is it a good practice to maintain an exact copy of the struct (struct of elbv2 package) with few changes?