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
This sample program demonstrates how to create multiple goroutines and how the goroutine scheduler behaves with three logical processors.
GO language program with example of Sort Functions for integer, strings and float64 data type
Program in Golang to print Pyramid of Numbers
5 Must-Know Blockchain Trends for 2024 and Beyond
Polymorphism in Go Programming Language
Golang program to print all Permutations of a given string
Most Helpful This Week
Example of Fscan, Fscanf, and Fscanln from FMT PackageRegular expression to extract all Non-Alphanumeric Characters from a StringFind out how many logical processors used by current processHow to declare empty Map in Go?Example to create custom errorGet Year, Month, Day, Hour, Min and Second from current date and time.How to check UPPERCASE characters in a string in Golang?How to check lowercase characters in a string in Golang?How To Make an HTTP Server in Golang?Regular expression to extract domain from URL