Golang: how to follow location with cookie

2019-02-02 09:25发布

问题:

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?

回答1:

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))
}