In order to get multiple values from a header, we have to use a standard map expression. However, we need to be aware that keys are canonicalized (header["My-Key"]) otherwise header["my-key"] will not return any value. Or need to use textproto.CanonicalMIMEHeaderKey() explicitly.
header.Get(key) allows to get the first value and internally uses textproto.CanonicalMIMEHeaderKey to canonicalize the key before getting the value.
Is there a reason not to provide, something likeheader.GetValues(key), which returns []string?
Both the http.Header and textproto.MIMEHeader types specify that "[t]o access multiple values of a key, or to use non-canonical keys, access the map directly." Also, given how simply this function can be written yourself, why is it necessary to include it in the standard library?
func GetValues(h textproto.MIMEHeader, key string) []string {
if h == nil {
return nil
}
return h[textproto.CanonicalMIMEHeaderKey(key)]
}
Thanks @smasher164 for the explanation.
When using http.Client to invoke an HTTP API endpoint, all keys in the http.Response.Header are canonicalized automatically although the API server returns a non-canonicalized header key.
I thought it would be useful to provide such method so developers don't have to worry about case sensitivity when providing header key to get multiple values just like getting a single value.
I'm cool with having a utility function to perform the same. Hope no other developers would hit the similar confusion as I did.
I'd prefer to change the representation of net/http (and probably net/textproto) Header to not be a map and instead be a struct containing an internal map (along with other stuff), and enforce that we only store canonicalized keys.
That's part of #23707.
That said, a new method for now sounds fine. GetValues is a little weird in that the existing method Get isn't GetValue. GetAll? GetMulti? Just Values? (we prefer to avoid Get in general)
I'm in favor of calling it Values, since it reads nicely when called as header.Values(key).
I like Values, but the downside is that it doesn't sort next to Get in the godoc. Not the end of the world, I suppose.
Change https://golang.org/cl/200760 mentions this issue: net/http, net/textproto: add a Header method to get multiple values []string, with canonicalized key
Change https://golang.org/cl/217129 mentions this issue: doc/go1.14: mention net/http.Header.Values, net/textproto.MIMEHeader.Values
Most helpful comment
I like
Values, but the downside is that it doesn't sort next toGetin the godoc. Not the end of the world, I suppose.