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
Explain in Brief Golang error handling best practices
Golang program for implementation of Rabin-Karp
How to slice elements in Golang?
How to check specific field exist in struct?
How to get first and last element of slice in Golang?
How do you handle HTTP client server logging in Go?
GO Program to Calculate Sum of Natural Numbers Using for.....Loop
React JS Count number of checkboxes are checked
How do you set headers in an HTTP response in Go?
Go program to find Forward(A) record of a domain
Most Helpful This Week
Strip all white spaces, tabs, newlines from a stringHow to fetch an Integer variable as String in Go?How to print struct variables data in Golang?Example to compare Println vs PrintfSelect single argument from all arguments of variadic functionSubtract N number of Year, Month, Day, Hour, Minute, Second, Millisecond, Microsecond and Nanosecond to current date-time.Passing multiple string arguments to a variadic functionExample to use Weekday and YearDay functionHow to check if a string contains certain characters in Golang?How to use array in Go Programming Language?