简体   繁体   English

如何全局设置cookiejar,以便在每个http.Client请求中都存在cookie

[英]How to set cookiejar globally so that the cookies are present in every http.Client request

I am new here and a bit confused with setting cookie jar gloabally. 我在这里是新来的,有点困惑地设置饼干罐。 I am using cookiejar from the http package and this is my implementation from other docs available in setting the cookies as jar in http.Client. 我正在使用http包中的cookiejar,这是我在http.Client中将cookie设置为jar时获得的其他文档的实现。

    jar, _ := cookiejar.New(nil)
    client := &http.Client{
      Jar: jar,
    }
    req, _ := http.NewRequest("GET", request_url, nil)
    q := req.URL.Query()
    q.Add("authtoken", token)
    req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
    req.URL.RawQuery = q.Encode()
    res, _ := client.Do(req)
    defer res.Body.Close() 
    fmt.Println(res.Cookies()) // can see the cookies here

What I am trying to achieve here is to have this declared gloabally so that once the jar is set the subsequent client request will have the cookies. 我在这里想要实现的是在全局范围内进行声明,以便一旦设置了jar,则后续的客户端请求将具有cookie。 If I place it in any other function it gets sets to nil again. 如果我将其放置在任何其他函数中,它将再次设置为nil。

    jar, _ := cookiejar.New(nil)
    client := &http.Client{
      Jar: jar,
    }

Any best practise available in how to do this? 有什么最佳实践可供选择吗? Thank you. 谢谢。

http.Client is designed to be reused: http.Client被设计为可重用:

The Client's Transport typically has internal state (cached TCP connections), so Clients should be reused instead of created as needed. 客户端的传输通常具有内部状态(缓存的TCP连接),因此应重新使用客户端,而不是根据需要创建客户端。 Clients are safe for concurrent use by multiple goroutines. 客户端可以安全地被多个goroutine并发使用。

So simply just create / configure an http.Client , and reuse it everywhere where you want your cookiejar to work. 因此,只需创建/配置http.Client ,然后在您希望其cookiejar工作的任何地方重复使用它即可。

If one configured http.Client doesn't fit all your use cases, then create as many clients that do. 如果一个配置的http.Client不能满足您的所有用例,则创建尽可能多的客户端。 To ensure the same cookiejar is used, you may create a client "factory" function which ensures the returned http.Client will have the Jar set. 为了确保使用相同的cookiejar,您可以创建一个客户端“ factory”功能,以确保返回的http.Client将具有Jar设置。

Undoable (at least you cannot force the use of your client). 不可执行(至少您不能强制使用客户端)。

Nearest is injecting your client into net/http.DefaultClient. 最近是将您的客户端注入net / http.DefaultClient。

Most sensible is to use icza's solution. 最明智的是使用icza的解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM