dongyong8071 2018-07-13 12:58
浏览 123

在Go中添加默认的HTTP标头

I'm taking my first steps in Go and would like to consume a REST API. The server requires each request to be authorized with a bearer token.

How can I add this header to the client so that every request uses this token?

import "net/http"

const accessToken = "MY_DEMO_TOKEN"

func main() {
    customHeader := http.Header{}
    customHeader.Add("Authorization: Bearer %s", accessToken)
    client := &http.Client{
        Timeout: time.Second*10,
    }
}
  • 写回答

2条回答 默认 最新

  • douju6850 2018-07-13 13:38
    关注

    You can decorate the client's Transport. For instance:

    package main
    
    import "net/http"
    
    func main() {
            client := http.DefaultClient
    
            rt := WithHeader(client.Transport)
            rt.Set("Authorization", "Bearer <token>")
            client.Transport = rt
    
            client.Get("http://example.com")
    }
    
    type withHeader struct {
            http.Header
            rt http.RoundTripper
    }
    
    func WithHeader(rt http.RoundTripper) withHeader {
            if rt == nil {
                    rt = http.DefaultTransport
            }
    
            return withHeader{Header: make(http.Header), rt: rt}
    }
    
    func (h withHeader) RoundTrip(req *http.Request) (*http.Response, error) {
            for k, v := range h.Header {
                    req.Header[k] = v
            }
    
            return h.rt.RoundTrip(req)
    }
    

    For the specific purpose of authorization tokens, you might be interested in the golang.org/x/oauth2 package, which does essentially the same, but also supports automatic token renewal:

    package main
    
    import (
            "context"
    
            "golang.org/x/oauth2"
    )
    
    func main() {
            ctx := context.Background()
            client := oauth2.NewClient(ctx, oauth2.StaticTokenSource(&oauth2.Token{
                    AccessToken: "<your token>",
                    TokenType:   "Bearer",
            }))
    
            client.Get("http://example.com")
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?
  • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算