How to Emulate cURL's Cookie-Based Location Following in Go?

DDD
Release: 2024-11-05 07:26:02
Original
384 people have browsed it

How to Emulate cURL's Cookie-Based Location Following in Go?

Emulating 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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!