Get/Set HTTP Headers in Go Request

HTTP headers, we all need ’em 😉

Here’s how you can get and set these headers within your Go requests. These include request coming into your router handlers and requests you are sending out to other systems through net/http. This can be thought of as being the same as reading headers from a request and creating new ones.

First we’ll start with reading them from the request.

Get

1
r.Header.Get("X-Name")

Example:

1
2
3
4
5
6
7
func ExampleHandler(w http.ResponseWriter, r *http.Request) {
	name := r.Header.Get("X-Name")
	if name == "" {
		log.Fatal("Header not set")
	}
	log.Println(name)
}

The headers are accessible through the Header part of the request - and from here you can get a specific header, through calling .Get().

If the header isn’t set, or is empty, it will return an empty string.

Set

1
r.Header.Set("X-Name", "gophercoding")

Example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
req, err := http.NewRequest(http.MethodGet, "https://gophercoding.com", nil)
if err != nil {
	return err
}

req.Header.Add("Content-Type", "application/json")

client := &http.Client{Timeout: 10 * time.Second}
resp, err := client.Do(req)

// etc...

You can call .Set() in a similar way to the reading the headers, but you will also need to pass in the value to set it to. In our example above we set the content type of the request to json.