Preserve Case When Working With HTTP Headers in Go
Dec 27, 2023 · 1 min readWhen you’re manipulating the HTTP headers with methods like Set()
, Add()
, etc., in Go, you’ll find that they’re automatically canonicalized. Canonicalization converts the first letter and any letter following a hyphen to uppercase, and every other letters to lowercase.
For example:
Will be transformed into this:
This is caused by Go passing your key through CanonicalMimeHeaderKey
before calling your methods.
This is fine and all as HTTP headers are case-insensitive. But sometimes, you might find yourself in a situation where you’re forced to work with case-sensitive headers.
In that case, you can modify the HTTP headers like this:
This is possible because the Header’s type is actually map[string][]string
, meaning it’s just a map
with key of type string
and value of type []string
.