18

In case the response to an http request is a redirection (http code 302) with a cookie,

how can you instruct your Go client to follow the new location with the cookie that has been received?

in CURL, this can be easily achieved by setting the client with:

 COOKIEFILE = ""
 AUTOREFERER = 1
 FOLLOWLOCATION = 1

how can you do that in Go?

Daniele B
  • 19,801
  • 29
  • 115
  • 173

1 Answers1

34

With Go 1.1 you can use the net/http/cookiejar for that.

Here is a working example:

package main

import (
    "golang.org/x/net/publicsuffix"
    "io/ioutil"
    "log"
    "net/http"
    "net/http/cookiejar"
)

func main() {
    options := cookiejar.Options{
        PublicSuffixList: publicsuffix.List,
    }
    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()
    if err != nil {
        log.Fatal(err)
    }
    log.Println(string(data))
}
Gustavo Niemeyer
  • 22,007
  • 5
  • 57
  • 46