How do you set cookies in an HTTP request with an HTTP client in Go?

To set cookies in an HTTP request with an HTTP client in Go, you can create a new http.Cookie struct and add it to the http.Client's Jar field. Here's an example:
Set cookies in an HTTP

Example

cookie := &http.Cookie{
    Name:  "session_id",
    Value: "12345",
}

client := &http.Client{
    Jar:       &cookiejar.Jar{},
    Transport: &http.Transport{},
}

req, err := http.NewRequest("GET", "https://www.example.com", nil)
if err != nil {
    // handle error
}

client.Jar.SetCookies(req.URL, []*http.Cookie{cookie})

resp, err := client.Do(req)
if err != nil {
    // handle error
}
defer resp.Body.Close()

// read response

In this example, a new http.Cookie struct is created with the name "session_id" and value "12345". An http.Client is then created with an empty cookiejar and http.Transport.

An http.Request is created with the http.NewRequest() function. The SetCookies() method of the http.CookieJar is then called to add the cookie to the request. The SetCookies() method takes the URL of the request and a slice of *http.Cookie pointers.

Finally, the http.Client's Do() method is called with the request, which sends the request with the cookie to the server. The response is stored in the resp variable for further processing.

Note that the http.Client's Jar field is used to manage cookies. By default, the http.Client uses a nil cookie jar, which means that it won't handle cookies. In this example, we create a new cookiejar and pass it to the http.Client's Jar field. This allows the http.Client to automatically handle cookies for subsequent requests.


Most Helpful This Week