How can I make a request with a bearer token in Go

前端 未结 3 1543
不思量自难忘°
不思量自难忘° 2021-02-12 16:44

I need to make a GET request to an API with a bearer token in the authorization request. How can I do this in Go? I have the following code, but I haven\'t had success.

3条回答
  •  一整个雨季
    2021-02-12 16:56

    I had to add a client.CheckRedirect Function(seen below) in order to pass the Bearer token to the API.

    bearer := "Bearer " + token
    
        req, err := http.NewRequest("GET", url, bytes.NewBuffer(nil))
        req.Header.Set("Authorization", bearer)
        req.Header.Add("Accept", "application/json")
    
        client := &http.Client{}
    
    
        client.CheckRedirect = func(req *http.Request, via []*http.Request) error {
            for key, val := range via[0].Header {
                req.Header[key] = val
            }
            return err
        }
        resp, err := client.Do(req)
        if err != nil {
            log.Println("Error on response.\n[ERRO] -", err)
        } else {
            defer resp.Body.Close()
            data, _ := ioutil.ReadAll(resp.Body)
            fmt.Println(string(data))
        }
    }
    

提交回复
热议问题