douli4852 2019-01-08 09:20
浏览 107
已采纳

使用客户端为每个HTTP请求添加标头

I know that I can add headers to each HTTP request manually using

cli := &http.Client{}
req, err := http.NewRequest("GET", "https://myhost", nil)
req.Header.Add("X-Test", "true")
if err != nil {
    panic(err)
}
rsp, err := cli.Do(req)

but I want to add this header automatically for each HTTP request in my app.

What is the best way to do it?

  • 写回答

2条回答 默认 最新

  • dtewnsdf47253 2019-01-08 09:40
    关注

    I'm aware of three possible solutions to this. In (my) order of preference:

    1. Wrap http.NewRequest with custom code that adds desired headers:

      func MyRequest(method, path url, body io.Reader) (*http.Request, error) {
          req, err := http.NewRequest(method, path, body)
          if err != nil {
              return nil, err
          }
          req.Header.Add("X-Test", "true")
          return req, nil
      }
      

      This approach has the advantage of being straight-forward, non-magical, and portable. It will work with any third-party software, that adds its own headers, or sets custom transports.

      The only case where this won't work is if you depend on a third-party library to create your HTTP requests. I expect this is rare (I don't recall ever running into this in my own experience). And even in such a case, perhaps you can wrap that call instead.

    2. Wrap calls to client.Do to add headers, and possibly any other shared logic.

      func MyDo(client *http.Client, req *http.Request) (*http.Response, error) {
          req.Header.Add("X-Test", "true")
          // Any other common handling of the request
          res, err := client.Do(req)
          if err != nil {
              return nil, err
          }
          // Any common handling of response
          return res, nil
      }
      

      This approach is also straight-forward, and has the added advantage (over #1) of making it easy to reduce other boilerplate. This general method can also work very well in conjunction with #1. One possible draw-back is that you must always call your MyDo method directly, meaning you cannot rely on third party software which calls http.Do itself.

    3. Use a custom http.Transport

      type myTransport struct{}
      
      func (t *myTransport) RoundTrip(req *http.Request) (*http.Response, error) {
          req.Header.Add("X-Test", "true")
          return http.DefaultTransport.RoundTrip(req)
      }
      

      Then use it like this:

      client := &Client{Transport: &myTransport{}}
      req := http.NewRequest("GET", "/foo", nil)
      res, err := client.Do(req)
      

      This approach has the advantage of working "behind the scenes" with just about any other software, so if you rely on a third-party library to create your http.Request objects, and to call http.Do, this may be your only option.

      However, this has the potential disadvantage of being non-obvious, and possibly breaking if you're using any third-party software which also sets a custom transport (without bothering to honor an existing custom transport).

    Ultimately, which method you use will depend on what type of portability you need with third-party software. But if that's not a concern, I suggest using the most obvious solution, which, by my estimation, is the order provided above.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 为啥画版图在Run DRC会出现Connect Error?可我Calibre的hostname和计算机的hostname已经设置成一样的了。
  • ¥20 网站后台使用极速模式非常的卡
  • ¥20 Keil uVision5创建project没反应
  • ¥15 mmseqs内存报错
  • ¥15 vika文档如何与obsidian同步
  • ¥15 华为手机相册里面的照片能够替换成自己想要的照片吗?
  • ¥15 陆空双模式无人机飞控设置
  • ¥15 sentaurus lithography
  • ¥100 求抖音ck号 或者提ck教程
  • ¥15 关于#linux#的问题:子进程1等待子进程A、B退出后退出(语言-c语言)