2012-09-25 44 views
2

來自net/http的源代碼。 http.Header的定義是map[string][]string。對?爲什麼http.Header中片的長度返回0?

但爲什麼go run下面的代碼,我得到的結果是:

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

如果你不確定你的結構的內容,請嘗試使用['%#v'(http://golang.org/pkg/fmt/ #打印)格式字符串,它可以很好地打印所有具有名稱的值。例子:['fmt.Printf(「%#v \ n」,header)'](http://play.golang.org/p/vZWWRiV_sQ) – nemo

回答

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

評論也許應該儘管移動..

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"}