Home > front end >  Converting untyped string constant to int in Go
Converting untyped string constant to int in Go

Time:10-06

I have an API request that returns a refresh_token, 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)
}

CodePudding user response:

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"])
  •  Tags:  
  • go
  • Related