In Go, you can encounter situations where an HTTP response to a request redirects (HTTP code 302) and sets a cookie. To handle this scenario, you may want to follow the new location with the received cookie.
To accomplish this:
1. Import the cookiejar Package:
<code class="go">import "golang.org/x/net/publicsuffix" import "net/http/cookiejar"</code>
2. Create a New Cookie Jar:
<code class="go">jar, err := cookiejar.New(&cookiejar.Options{ PublicSuffixList: publicsuffix.List, }) if err != nil { log.Fatal(err) }</code>
3. Create an HTTP Client with the Cookie Jar:
<code class="go">client := http.Client{Jar: jar}</code>
4. Send the HTTP Request:
<code class="go">resp, err := client.Get("http://dubbelboer.com/302cookie.php") if err != nil { log.Fatal(err) }</code>
5. Access the Response Data:
<code class="go">data, err := ioutil.ReadAll(resp.Body) resp.Body.Close() if err != nil { log.Fatal(err) } log.Println(string(data))</code>
By utilizing the cookiejar, Go ensures that the client follows the redirection and maintains the cookie during the process, allowing you to handle cookie-based redirections effectively.
The above is the detailed content of How to Follow Location with Cookies in Go?. For more information, please follow other related articles on the PHP Chinese website!