Go has several ways of sending requests, including some convenient methods such as:
http.Get()http.Head()http.Post()http.PostForm()
However, these don’t let you add headers to requests! If you need customization of the HTTP method or headers, you need to use http.NewRequest().
There are three parts to this:
- Create a request using
http.NewRequest()where you specify the HTTP method and URL - Add headers to the request with
Header.Set() - Send the request using
http.Client{}
Here’s a full example:
| |
req.Header.Set() can be used to set a header but will overwrite any existing value for that header.
req.Header.Add() can be used to add a value to a header and will append to any existing value for that header.
For the purposes of this blog post we only need to worry about setting the header once, hence the usage of req.Header.Set().
Similar to my “Using time.Sleep() in Go” post, I wrote this up because the Go docs are too dense and I just needed one full example to understand it and get going.