How do you read cookies in an HTTP request with an HTTP client in Go?
To read cookies in an HTTP request with an HTTP client in Go, you can use the http.Response struct's Cookies() method. Here's an example:
Read cookies in an HTTP request
Example
client := &http.Client{
Transport: &http.Transport{},
}
req, err := http.NewRequest("GET", "https://www.example.com", nil)
if err != nil {
// handle error
}
resp, err := client.Do(req)
if err != nil {
// handle error
}
defer resp.Body.Close()
cookies := resp.Cookies()
for _, cookie := range cookies {
fmt.Printf("Cookie: %s=%s\n", cookie.Name, cookie.Value)
}
In this example, an http.Client is created with a http.Transport. An http.Request is then created with the http.NewRequest() function.
The request is sent with the http.Client's Do() method, and the response is stored in the resp variable. The Cookies() method is then called on the http.Response object to get a slice of *http.Cookie pointers.
The for loop is then used to iterate over each cookie in the slice, and the cookie name and value are printed to the console.
Note that cookies can only be read from an http.Response object, not from an http.Request object. If you want to send cookies with a subsequent request, you can create a new http.Cookie struct and add it to the http.Client's Jar field, as described in the previous answer.
Most Helpful This Week
Golang program for implementation of Merge Sort
Polymorphism in Go Programming Language
Go program to find CNAME record of a domain
How do you handle HTTP server caching in Go?
Example: How to use TeeReader from IO Package in Golang?
How to use WaitGroup to delay execution of the main function until after all goroutines are complete.
Most Helpful This Week
Normal function parameter with variadic function parameterHow to convert Boolean Type to String in Go?How to update content of a text file?Sierpinski triangle in Go Programming LanguageHow to check if a map contains a key in Go?Golang Get current Date and Time in EST, UTC and MST?Add N number of Year, Month, Day, Hour, Minute, Second, Millisecond, Microsecond and Nanosecond to current date-timeHow to import structs from another package in Go?How to fetch an Integer variable as String in Go?How to convert Colorful PNG image to Gray-scale?