From the source code of net/http. The definition of http.Header
is map[string][]string
. Right?
But why go run
below code, I get the result:
0
2
func main() {
var header = make(http.Header)
header.Add("hello", "world")
header.Add("hello", "anotherworld")
var t = []string {"a", "b"}
fmt.Printf("%d
", len(header["hello"]))
fmt.Print(len(t))
}
if you try
fmt.Println(header)
you'll notice that the key has been capitalized. This is actually noted in the documentation of net/http.
// HTTP defines that header names are case-insensitive.
// The request parser implements this by canonicalizing the
// name, making the first character and any characters
// following a hyphen uppercase and the rest lowercase.
This can be found in the comment on the field Header of type Request.
http://golang.org/pkg/net/http/#Request
Comment should probably be moved though..
Take a look at the reference of http.Header
and the code of Get
:
Get gets the first value associated with the given key. If there are no values associated with the key, Get returns "". To access multiple values of a key, access the map directly with CanonicalHeaderKey.
So it helps to use http.CanonicalHeaderKey
instead of strings for keys.
package main
import (
"net/http"
"fmt"
)
func main() {
header := make(http.Header)
var key = http.CanonicalHeaderKey("hello")
header.Add(key, "world")
header.Add(key, "anotherworld")
fmt.Printf("%#v
", header)
fmt.Printf("%#v
", header.Get(key))
fmt.Printf("%#v
", header[key])
}
The output:
http.Header{"Hello":[]string{"world", "anotherworld"}}
"world"
[]string{"world", "anotherworld"}