Home >Backend Development >Golang >How to Follow Redirections with Cookies in Go?
In handling HTTP requests, it's common to encounter redirects that carry cookies. This poses a challenge when using Golang, as the default behavior is to drop cookies during redirects. To overcome this, you can utilize the net/http/cookiejar package, introduced in Go 1.1.
With the cookiejar package, you can configure a client to automatically follow redirects while preserving the received cookies. To achieve this:
Here's an illustrative example:
<code class="go">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)) }</code>
By using this approach, your Go client will automatically follow redirects and maintain the received cookies, similar to the behavior in cURL when setting COOKIEFILE, AUTOREFERER, and FOLLOWLOCATION.
The above is the detailed content of How to Follow Redirections with Cookies in Go?. For more information, please follow other related articles on the PHP Chinese website!