Golang: how to follow location with cookie

后端 未结 1 1299
忘掉有多难
忘掉有多难 2020-12-28 19:19

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 cooki

相关标签:
1条回答
  • 2020-12-28 19:49

    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))
    }
    
    0 讨论(0)
提交回复
热议问题