Home > Article > Backend Development > How to Emulate cURL's Cookie-Based Location Following in Go?
Problem:
When receiving a redirect (HTTP code 302) with an accompanying cookie in the response, how can a Go client follow the new location while utilizing the received cookie?
Answer:
In Go 1.1 and later, the net/http/cookiejar package provides a solution for this:
<code class="go">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>
This code snippet effectively emulates CURL's cookie-based location following behavior by creating a cookie jar (jar) that stores the received cookie. When the client follows the redirect, it sends the stored cookie along with the request, allowing it to access the new location with the appropriate permissions.
The above is the detailed content of How to Emulate cURL's Cookie-Based Location Following in Go?. For more information, please follow other related articles on the PHP Chinese website!