Map 为什么http.Header中的切片长度返回0?

Map 为什么http.Header中的切片长度返回0?,map,go,Map,Go,来自net/http的源代码。http.Header的定义是map[string][]string。对吧? 但是为什么go run在代码下面,我得到了结果: 0 二, 如果你尝试 fmt.Println(header) 您会注意到该键已大写。事实上,在net/http的文档中已经注意到了这一点 // HTTP defines that header names are case-insensitive. // The request parser implements this by cano

来自net/http的源代码。
http.Header
的定义是
map[string][]string
。对吧?

但是为什么
go run
在代码下面,我得到了结果:

0

二,

如果你尝试

fmt.Println(header)
您会注意到该键已大写。事实上,在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.
这可以在Request类型的字段头上的注释中找到


注释可能会被移动。

请查看以下内容的参考和代码:

Get获取与给定键关联的第一个值。如果没有与键关联的值,Get将返回“”。要访问一个键的多个值,请直接使用CanonicalHeaderKey访问映射

因此,使用字符串代替键是有帮助的

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\n", header)
    fmt.Printf("%#v\n", header.Get(key))
    fmt.Printf("%#v\n", header[key])
}
输出:

http.Header{"Hello":[]string{"world", "anotherworld"}}
"world"
[]string{"world", "anotherworld"}

如果不确定结构的内容,请尝试使用格式字符串,它可以很好地打印所有带名称的值。例子:
http.Header{"Hello":[]string{"world", "anotherworld"}}
"world"
[]string{"world", "anotherworld"}