dongsu4345 2018-07-21 01:51
浏览 80

如何在Go中使用承载令牌提出请求

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.

package main

import (
    "io/ioutil"
    "log"
    "net/http"
)

func main() {
    url := "https://api.globalcode.com.br/v1/publico/eventos"

    resp, err := http.Get(url)
    resp.Header.Add("Bearer", "token")
    if err != nil {
        log.Println("Erro ao realizar request.
[ERRO] -", err)
    }

    body, _ := ioutil.ReadAll(resp.Body)
    log.Println(string([]byte(body)))
}
  • 写回答

2条回答 默认 最新

  • doudou8081 2018-07-21 05:45
    关注

    For control over HTTP client headers, redirect policy, and other settings, create a Client:

    package main
    
    import (
        "io/ioutil"
        "log"
        "net/http"
    )
    
    func main() {
        url := "https://api.globalcode.com.br/v1/publico/eventos"
    
        // Create a Bearer string by appending string access token
        var bearer = "Bearer " + <ACCESS TOKEN HERE>
    
        // Create a new request using http
        req, err := http.NewRequest("GET", url, nil)
    
        // add authorization header to the req
        req.Header.Add("Authorization", bearer)
    
        // Send req using http Client
        client := &http.Client{}
        resp, err := client.Do(req)
        if err != nil {
            log.Println("Error on response.
    [ERRO] -", err)
        }
    
        body, _ := ioutil.ReadAll(resp.Body)
        log.Println(string([]byte(body)))
    }
    

    The Client's Transport typically has internal state (cached TCP connections), so Clients should be reused instead of created as needed. Clients are safe for concurrent use by multiple goroutines.

    A Client is higher-level than a RoundTripper (such as Transport) and additionally handles HTTP details such as cookies and redirects.

    For more information on Client and Transport check golang spec for net/http package

    评论

报告相同问题?

悬赏问题

  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥15 cmd cl 0x000007b
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line