Golang gotchas: Instantiating http.Header
Programming Estimated reading time: ~2 minutes
When creating http.Header instances directly, you better use the canonical form for the HTTP header keys. Otherwise this might lead to unexpected results.
Suppose you do the following:
header := http.Header{
"content-type": {"application/json"},
}
headerValue := header.Get("Content-Type") // headerValue = ""
In the case above header.Get
will return an empty string.
But instantiating http.Header
as outlined below works:
headers := http.Header{
"Content-Type": {"application/json"},
}
headerValue := headers.Get("CONTENT-TYPE") // headerValue = "application/json"
Here a call to headers.Get
will return “application/json”.
The behaviour is different because when http.Header
is instantiated directly, all header keys are expected
to be canonicalized already. Therefore it’s better to use the following patterns when using the http.Header
structure:
header := http.Header{
http.CanonicalHeaderKey("content-type"): {"application/json"},
}
// or
header := http.Header{}
header.Add("content-type", "whatever")
Also keep in mind that the header for an HTTP request can not be modelled as a hash map (e.g.
map[string]string
in Golang). That’s because a given HTTP header key might be present multiple times
in an HTTP header. The details can be found in RFC 9110 (HTTP Semantics).
Suppose we have the following HTTP header fields:
Example-Field: Foo, Bar
Example-Field: Baz
Here we have two field lines, both with the field name “Example-Field”. The first field line has a field line value of “Foo, Bar”, while the second field line value is “Baz”. The field value for “Example-Field” is the list “Foo, Bar, Baz”.
You might ask yourself what’s the use case for sending an HTTP request which contains multiple HTTP header fields with the same name / key. Well, it’s commonly used for the Set-Cookie HTTP response header for example. Because a lot of HTTP servers set more than one cookie…
A note about Netcup (advertisement)
Netcup is a German hosting company. Netcup offers inexpensive, yet powerfull web hosting packages, KVM-based root servers or dedicated servers for example. Using a coupon code from my Netcup coupon code web app you can even save more money (6$ on your first purchase, 30% off any KVM-based root server, ...).