How to Set Headers in HTTP GET Request

To set headers in HTTP GET Request, you can use the req.Header.Set(“name”, “value”) function. You can use the http.NewRequest() function to create a new request and then 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.

If you don’t need an authorization token for the API, you’re working with; you should remove the Authorization header line.

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.

Leave a Comment