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

时间:2012-09-25 15:36:44

标签: map go

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

但为什么go run低于代码,我得到了结果:

  

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\n", len(header["hello"]))
    fmt.Print(len(t))
}

2 个答案:

答案 0 :(得分:3)

如果你尝试

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.

这可以在类型请求的字段标题的注释中找到。

http://golang.org/pkg/net/http/#Request

虽然应该移动评论..

答案 1 :(得分:3)

查看http.Header的引用和Get的代码:

  

获取与给定键关联的第一个值。如果没有与该键相关联的值,则Get返回“”。要访问密钥的多个值,请使用CanonicalHeaderKey直接访问地图。

因此,使用http.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"}
相关问题