Empty HTTP Headers in Go
Here is a technique for checking for the presence of a HTTP header in a Go request, even if the header has no value.
If there’s a header in a HTTP request that has no value, the parser used by Go will store the header against an empty string value. This string value is available using the Values()
method: using the Get()
method will not work as that will return an empty string if the header is not present in the request, make it ambiguous for existential tests if empty header values are allowed.
The Values()
method can be used to return all the values of a header. This is useful for cases when a header appears multiple times in a request, but it’s also useful here as an empty slice is returned if the header does not appear. In which case, the way to test for the presence of a header can be done using the following line of code:
len(req.Header.Values("My-Header")) > 0
Where “My-Header” is the header you are looking for.