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

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.

    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. If I place it in any other function it gets sets to nil again.

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

Any best practise available in how to do this? Thank you.

2个回答



http.Client </ code> 被设计为可重用:</ p>


客户端的传输通常具有内部状态(缓存的TCP连接), 因此,应该重新使用客户端,而不是根据需要创建客户端。 客户端可以安全地被多个goroutine并发使用。</ strong> </ p>
</ blockquote>

因此,只需创建/配置 http.Client </ code>,然后 </ p>

如果在其中配置的 http.Client </ code>不能满足您的所有用例,则请创建尽可能多的客户端 做。 为了确保使用相同的cookiejar,您可以创建一个客户端“ factory”功能,以确保返回的 http.Client </ code>将具有Jar设置。</ p>
</ div>

展开原文

原文

http.Client is designed to be reused:

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.

So simply just create / configure an http.Client, and reuse it everywhere where you want your cookiejar to work.

If one configured http.Client doesn't fit all your use cases, then create as many clients that do. 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.



不可(至少您不能强制</ em>使用客户端)。</ p>
\ n

最近将您的客户端注入net / http.DefaultClient。</ p>

最明智的方法是使用icza的解决方案。</ p>
</ div>

展开原文

原文

Undoable (at least you cannot force the use of your client).

Nearest is injecting your client into net/http.DefaultClient.

Most sensible is to use icza's solution.

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐