0

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{})
codec
  • 7,978
  • 26
  • 71
  • 127
  • Possible duplicate of [How to get JSON response in Golang](http://stackoverflow.com/questions/17156371/how-to-get-json-response-in-golang) – Martin Tournoij Nov 17 '16 at 10:29
  • I tried this. Adding more details – codec Nov 17 '16 at 10:42
  • Your JSON does not represent an array of strings. Try `type target []interface{}` instead. – Franck Jeannin Nov 17 '16 at 10:51
  • No I am still getting a blank array as response. and If I print the responsebody using reading `respbody, err := ioutil.ReadAll(resp.Body)` I am able to see the entire response. but decode is not working. The response has more nested arrays in it , does the target struct change accordingly? – codec Nov 17 '16 at 10:58
  • @love2code In your first example you should use c.String() to directly return the string from your 3rd party. In your second example, you can't `Decode` the JSON into a string slice as it's not a string array but an array of objects - you should treat it as such. – xen Nov 17 '16 at 14:31

1 Answers1

1

Your first example does not work because you are trying to marshal a string as JSON which will only escape the string. Rather, change the last line to

c.String(200, string(respbody))

This won't change the string you are receiving from your third party at all and will just return it. See here for the difference.

If you want to inspect the data as it travels through your program, you have to first decode the JSON string into an array of structs like this:

type Response []struct {
    Continent string `json:"Continent"`
    Countries []struct {
        Country string `json:"Country"`
    } `json:"Countries"`
}
xen
  • 625
  • 1
  • 7
  • 18