0

I have an API request that returns a refresh_token inside array, which looks something like this:

[
  {
    "refresh_token" : "C61551CEA183EDB767AA506926F423B339D78E2E2537B4AC7F8FEC0C29988819"
  }
]

I need to access this refresh_token's value, and use it to query another API.

To do this, I'm attempting to first 'ReadAll' the response body, and then access the key inside of it by calling 'refreshToken'.

However, it's not working. Does anyone know how to resolve this as I can't figure it out?

Here's my code:

func Refresh(w http.ResponseWriter, r *http.Request) {

    client := &http.Client{}

    // q := url.Values{}

    fetchUrl := "https://greatapiurl.com"

    req, err := http.NewRequest("GET", fetchUrl, nil)

    if err != nil {
        fmt.Println("Errorrrrrrrrr")
        os.Exit(1)
    }

    req.Header.Add("apikey", os.Getenv("ENV"))
    req.Header.Add("Authorization", "Bearer "+os.Getenv("ENV"))

    resp, err := client.Do(req)

    if err != nil {
        fmt.Println("Ahhhhhhhhhhhhh")
        os.Exit(1)
    }

    respBody, _ := ioutil.ReadAll(resp.Body)

    fmt.Println(respBody["refresh_token"])

    w.WriteHeader(resp.StatusCode)
    w.Write(respBody)
}
MenyT
  • 1,653
  • 1
  • 8
  • 19
Jon Nicholson
  • 927
  • 1
  • 8
  • 29
  • 4
    `ioutil.ReadAll()` will read the response body and return it as a byte slice, that is of type `[]byte`. If the body contains JSON text, you need to unmarshal it. Use the `encoding/json` package to do that. – icza Oct 05 '21 at 15:35
  • you need to unmarshal that response body into ```map[string]interface{}``` then you can access the key you want. – Dipto Mondal Oct 05 '21 at 15:49
  • I don't think this is right... It would be if it's stored into a plain json string but it's inside of an array. That must mean it's different surely? – Jon Nicholson Oct 05 '21 at 16:21
  • Does this answer your question? [How to get JSON response from http.Get](https://stackoverflow.com/questions/17156371/how-to-get-json-response-from-http-get) – Hymns For Disco Oct 05 '21 at 16:27

1 Answers1

2

If you do not need it as custom type you can cast it as []map[string]string

respBody, _ := ioutil.ReadAll(resp.Body)
var body []map[string]string
json.Unmarshal(respBody, &body)
fmt.Println(body[0]["refresh_token"])
MenyT
  • 1,653
  • 1
  • 8
  • 19