To set headers in HTTP GET Request, use the “http.Header” type. You can use the “http.NewRequest()” function to create a new request and modify the request’s Header field before sending it using the http.Client’s “Do()” method.
Example
package main
import (
"fmt"
"io/ioutil"
"net/http"
"os"
)
func main() {
url := "https://openlibrary.org/works/OL18020194W/ratings.json"
// Create a new GET request
req, err := http.NewRequest("GET", url, nil)
if err != nil {
fmt.Fprintf(os.Stderr, "Error creating request: %v\n", err)
return
}
// Set headers
req.Header.Set("User-Agent", "MyCustomUserAgent")
req.Header.Set("Authorization", "Bearer your_token_here")
req.Header.Set("Accept", "application/json")
// Create an HTTP client
client := &http.Client{}
// Send the request using the client
resp, err := client.Do(req)
if err != nil {
fmt.Fprintf(os.Stderr, "Error making request: %v\n", err)
return
}
defer resp.Body.Close()
// Read the response body
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Fprintf(os.Stderr, "Error reading response body: %v\n", err)
return
}
fmt.Println("Response:")
fmt.Println(string(body))
}
Output
Response:
{"summary": {"average": 4.316923076923077, "count": 650,
"sortable": 4.226742195317977},
"counts": {"1": 57, "2": 14, "3": 43, "4": 88, "5": 448}}
In the above code example, we saw how to make an HTTP GET request to the specified URL (https://openlibrary.org/works/OL18020194W/ratings.json) with custom headers using Go.
It sets the User-Agent, Authorization, and Accept headers and sends the request using the http.Client’s Do() method. Then, the response body is printed.
Remove the Authorization header line if you don’t need an authorization token for the API you’re working with.
How to set multiple headers at once in Go
To set multiple headers, you can use the “http.Header” map. This can be useful when you want to initialize multiple headers at once.
req.Header = http.Header{
"User-Agent": {"MyCustomUserAgent"},
"Accept": {"application/json"},
"Authorization": {"Bearer your_token_here"},
"Custom-Header": {"CustomValue"},
}
In this example, we initialized the req.Header field with an http.Header map containing multiple header key-value pairs.
That’s it.

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.