Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang: how to follow location with cookie

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?

like image 265
Daniele B Avatar asked Aug 24 '13 02:08

Daniele B


1 Answers

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))
}
like image 117
Gustavo Niemeyer Avatar answered Sep 23 '22 23:09

Gustavo Niemeyer