Reputation: 7271
I am using go http client to make get requests and the client has been initialised with a cookiejar however the response cookie array is empty. Has anyone got any idea what I am doing wrong?
jar, err := cookiejar.New(nil)
if err != nil {
log.Fatal(err)
}
s.http_client = &http.Client{Jar: jar}
resp, _ := s.http_client.Get(s.url)
fmt.Println(resp.Cookies())
returns an empty array although I can see cookies returned in firefox.
Upvotes: 3
Views: 4054
Reputation: 1323463
You create a cookiejar
, and you can use it as seen in "how to follow location with cookie":
jar, err := cookiejar.New(&options)
if err != nil {
log.Fatal(err)
}
client := http.Client{Jar: jar} // <============
resp, err := client.Get("http://dubbelboer.com/302cookie.php")
if err != nil {
log.Fatal(err)
}
data, err := ioutil.ReadAll(resp.Body)
resp.Body.Close()
(introduced with Go1.1 as in this answer)
An http.Client
struct has:
// Jar specifies the cookie jar.
// If Jar is nil, cookies are not sent in requests and ignored
// in responses.
Jar CookieJar
As 3of3 mentions, you don't need a cookiejar to fetch a cookie:
for _, cookie := range r.Cookies() {
fmt.Fprint(w, cookie.Name)
}
Check if the cookiejar is still empty after having read the full response body.
Upvotes: 5