I am using go-gin server in my golang project and fetching some data from an external API which returns an array as response
[
{
"Continent": "South America",
"Countries": [
{
"Country": "Argentina"
}
]
}
]
In my golang code here is how I am sending request and intercepting response
client := &http.Client{Transport: tr}
rget, _ := http.NewRequest("GET", "http://x.x.x.x/v1/geodata", nil)
resp, err := client.Do(rget)
if err != nil {
fmt.Println(err)
fmt.Println("Failed to send request")
}
defer resp.Body.Close()
respbody, err := ioutil.ReadAll(resp.Body)
c.Header("Content-Type", "application/json")
c.JSON(200, string(respbody))
This gives currect response but instead of an array I get a string with the entire array. So the response I get is
"[{\"Continent\":\"South America\",\"Countries\": [{\"Country\": \"Argentina\"} ] } ]"
How can intercept response as array instead of string? I even tried the following which did gave me an array but a blank one. The elements in my response body may be array as well as strings so the content is mixed.
type target []string
json.NewDecoder(resp.Body).Decode(target{})
defer resp.Body.Close()
c.Header("Content-Type", "application/json")
c.JSON(200, target{})