3

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.

cobie
  • 7,023
  • 11
  • 38
  • 60

1 Answers1

5

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.

Community
  • 1
  • 1
VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250
  • I do make use of the cookiejar as in the updated code preview but still get an empty array of cookies. – cobie Nov 29 '14 at 20:33
  • @cobie is it still empty *after* having read the response body? (I have edited the answer) – VonC Nov 29 '14 at 20:36
  • @cobie What does `resp.Cookies()` returns? (see end of edited answer) – VonC Nov 29 '14 at 21:07