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?
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))
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With