An HTTP header allows clients and servers to pass additional information with each request or response. Headers are just case-insensitive key-value pairs that pass additional metadata about the request or response.
HTTP requests from a web browser automatically carry with them many headers, including but not limited to:
As developers, we can also define custom headers in each request.
net/http PackageIn Go, the net/http package provides us with the necessary tools to work with HTTP headers. We can access headers through the Header type, which is essentially a map of string slices (map[string][]string). This allows us to perform various actions on our request and response headers such as retrieving, setting, and removing them.
// creating a new request
req, err := http.NewRequest("GET", "https://api.example.com/users", nil)
if err != nil {
fmt.Println("error creating request: ", err)
return
}
// setting a header on the new request
req.Header.Set("x-api-key", "123456789")
// making the request
client := http.Client{}
res, err := client.Do(req)
if err != nil {
fmt.Println("error making request: ", err)
return
}
defer res.Body.Close()
// reading a header from the response
header := res.Header.Get("last-modified")
fmt.Println("last modified: ", header)
// deleting a header from the response
res.Header.Del("last-modified")
Complete the getContentType function. It takes a pointer to a http.Response as input and should return the Content-Type header.
Use the .Get() method on the Response struct's Header field to get what you need.
Even though we've emphasized the need to close the response body, this is a mock response without a body. Trying to .Close() it will cause a panic.