How do you set headers in an HTTP request with an HTTP client in Go?
In Go, you can set headers in an HTTP request with an HTTP client using the http.Header type. Here's an example of how to set headers in an HTTP request:
Set headers in an HTTP request
Example
package main
import (
"fmt"
"net/http"
"strings"
)
func main() {
// Create an HTTP client
client := &http.Client{}
// Create an HTTP request with custom headers
req, err := http.NewRequest("GET", "https://example.com", nil)
if err != nil {
fmt.Println("Error creating HTTP request:", err)
return
}
req.Header.Add("Authorization", "Bearer <token>")
req.Header.Add("Content-Type", "application/json")
// Send the HTTP request
resp, err := client.Do(req)
if err != nil {
fmt.Println("Error sending HTTP request:", err)
return
}
// Read the response body
body, err := io.ReadAll(resp.Body)
if err != nil {
fmt.Println("Error reading HTTP response body:", err)
return
}
// Print the response body
fmt.Println(string(body))
}
In this example, we create an HTTP client using the http.Client type. We then create an HTTP request using the http.NewRequest function and set custom headers using the req.Header.Add method.
We set two headers in this example: an "Authorization" header with a bearer token, and a "Content-Type" header with a value of "application/json".
We then send the HTTP request using the client.Do method and read the response body using the io.ReadAll function. Finally, we print the response body to the console.
This is just a simple example, but the http.Header type provides many more methods for working with headers, such as getting, deleting, and iterating over header values.
Most Helpful This Week
How do you handle HTTP client server security in Go?
How do you handle HTTP redirects in Go?
How do you handle HTTP server health checks in Go?
How do you send an HTTP GET request with an HTTP client in Go?
How do you create an HTTP client in Go?
How do you handle HTTP client server alerting in Go?
How do you handle HTTP server HTTP/2 in Go?
How do you send an HTTP POST request with an HTTP client in Go?
How do you handle HTTP requests in Go?
How do you handle HTTP client server logging in Go?
Most Helpful This Week
How can I convert a string variable into Boolean, Integer or Float type in Golang?The return values of a function can be named in GolangHow to check string contains uppercase lowercase character in Golang?How to find the type of the variable by different ways in Golang?How to check if a string contains a numbers in Golang?How to remove symbols from a string in Golang?Example of Fscan, Fscanf, and Fscanln from FMT PackagePrint index and element or data from Array, Slice and MapExample: How to use TeeReader from IO Package in Golang?Generate a Keygen of 256 bits