How do you read headers from an HTTP response with an HTTP client in Go?
In Go, you can read headers from an HTTP response with an HTTP client using the http.Response type. Here's an example of how to read headers from an HTTP response:
Read headers from an HTTP response
Example
package main
import (
"fmt"
"net/http"
)
func main() {
// Create an HTTP client
client := &http.Client{}
// Send an HTTP request
resp, err := client.Get("https://example.com")
if err != nil {
fmt.Println("Error sending HTTP request:", err)
return
}
defer resp.Body.Close()
// Read headers from the HTTP response
contentType := resp.Header.Get("Content-Type")
server := resp.Header.Get("Server")
// Print headers
fmt.Println("Content-Type:", contentType)
fmt.Println("Server:", server)
}
In this example, we create an HTTP client using the http.Client type and send an HTTP request using the client.Get method. We then read the headers from the HTTP response using the resp.Header.Get method.
We read two headers in this example: the "Content-Type" header and the "Server" header. We print these headers to the console using the fmt.Println function.
It's important to note that the http.Response type also provides many more methods for working with HTTP responses, such as getting the status code, reading the response body, and getting the values of multiple headers at once.
Most Helpful This Week
GO Program to Swap Number Without Using Temporary Variables
Illustration of Sleeping Barber Problem in Golang
Example: How to use ReadFull from IO Package in Golang?
Type assertion in Go Programming Language
How to Convert string to float type in Go?
Multiple-value <function> in single-value context error in Golang
Syntax error: unexpected <token> error in Golang
Pass an Interface as an argument to a function in Go (Golang)
Golang HTTP GET request with parameters
Create and Print Multi Dimensional Slice in Golang
Most Helpful This Week
Example of Switch Case with Break in For LoopHow to convert Boolean Type to String in Go?How to import and alias package names?Golang download image from given URLGet Year, Month, Day, Hour, Min and Second from a specified dateSierpinski triangle in Go Programming LanguageHow to copy a map to another map?Split a character string based on change of characterHow to use for and foreach loop?Get Hours, Days, Minutes and Seconds difference between two dates [Future and Past]