我是新来的,有点混淆设置饼干jar gloabally.我正在使用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
Run Code Online (Sandbox Code Playgroud)
我在这里尝试实现的是将其全局声明,以便在设置jar后,后续客户端请求将具有cookie.如果我将它放在任何其他函数中,它将再次设置为nil.
jar, _ := cookiejar.New(nil)
client := &http.Client{
Jar: jar,
}
Run Code Online (Sandbox Code Playgroud)
如何做到这一点的最佳实践?谢谢.