2

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))
}
4

2 に答える 2

3

のリファレンスhttp.Headerとコードを見てくださいGet

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"}
于 2012-09-25T16:08:28.657 に答える
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

コメントはおそらく移動する必要があります..

于 2012-09-25T15:55:34.700 に答える