How do you read headers in an HTTP response in Go?
To read headers in an HTTP response in Go, you can use the http.Response struct's Header field, which contains a map of the response headers.
Here's an example:
Read headers in an HTTP response
Example
resp, err := http.Get("https://www.example.com")
if err != nil {
// handle error
}
defer resp.Body.Close()
contentType := resp.Header.Get("Content-Type")
fmt.Println("Content-Type header value:", contentType)
In this example, an HTTP GET request is made to https://www.example.com, and the response is stored in the resp variable. The Header field of the http.Response struct is then accessed to get the value of the Content-Type header using the Get() method. The Get() method returns an empty string if the header is not present in the response.
You can also iterate over all the headers in the response using a for loop:
Example
for key, values := range resp.Header {
fmt.Println("Header:", key)
for _, value := range values {
fmt.Println("Value:", value)
}
}
In this example, the range keyword is used to iterate over the keys and values in the Header map. The values are stored as slices, as a header can have multiple values with the same key. The inner for loop is used to iterate over each value in the slice.
Most Helpful This Week
Golang Web Server Example
How do you send an HTTP PUT request in Go?
How do you read cookies in an HTTP request with an HTTP client in Go?
How do you handle HTTP Client server load balancing in Go?
How do you send an HTTP PATCH request in Go?
How do you handle HTTP server shutdown gracefully in Go?
How do you read headers from an HTTP response with an HTTP client in Go?
What is an HTTP server in Go?
How do you set headers in an HTTP request with an HTTP client in Go?
How do you handle HTTP redirects in Go?
Most Helpful This Week
Simple example of Map initialization in GoConvert Int data type to Int16 Int32 Int64How to use function from another file golang?Split URL and Get Parameters from URLHow to use a mutex to define critical sections of code and fix race conditions?How to remove symbols from a string in Golang?Regular Expression to get a string between parentheses in GolangRegular expression to validate email addressHow to Unmarshal nested JSON structure?Different ways to convert Byte Array into String