i have some problems decoding the body of a http response. The response I get from using Insomnia looks like this:
[
{
"name": "monitoring",
"instances": [
{
"host": "ite00716.local",
"id": "2058b934-720f-47c5-a1da-3d1535423b83",
"port": 8080
}
]
},
{
"name": "app1",
"instances": [
{
"host": "172.20.10.2",
"id": "bc9a5859-8dda-418a-a323-11f67fbe1a71",
"port": 8081
}
]
}
]
When I use the following go code, the struct I decode to is empty. I'm not sure why. Please help me!
type Service struct {
Name string `json:"name"`
Instances []Instance `json:"instances"`
}
type Instance struct {
Host string `json:"host"`
Id string `json:"id"`
Port int `json:"port"`
}
func main() {
resp, err := http.Get("http://localhost:8080/services")
if err != nil {
panic(err)
}
defer resp.Body.Close()
var s Service
json.NewDecoder(resp.Body).Decode(&s)
fmt.Println(s)
}
Your json response is array of service
var s []Service
The problem may be that your variable is a Service, while your json represent an array of "Service"s.
Try declaring s as:
var s []Service;