2015-09-08 50 views
0

這一直困擾着我過去幾個小時,我試圖得到一個響應標題值。簡單的東西。如果我curl這個正在運行的服務器的請求,我看到了報頭組,與捲曲的-v標誌,但是當我嘗試使用Go的response.Header.Get()檢索標題,它顯示了一個空字符串"",與頭部的長度爲0。Golang:爲什麼response.Get(「headerkey」)在這段代碼中沒有返回值?

更讓我感到沮喪的是,當我打印出正文時,標題值實際上是在響應中設置的(如下所示)。

任何和所有這方面的幫助表示讚賞,在此先感謝。

我有這樣的代碼在這裏: http://play.golang.org/p/JaYTfVoDsq

其中包含以下內容:

package main 

import (
    "fmt" 
    "io/ioutil" 
    "net/http" 
    "net/http/httptest" 
) 

func main() { 
    mux := http.NewServeMux() 
    server := httptest.NewServer(mux) 
    defer server.Close() 

    mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { 
     r.Header.Set("Authorization", "responseAuthVal") 
     fmt.Fprintln(w, r.Header) 
    }) 

    req, _ := http.NewRequest("GET", server.URL, nil) 
    res, _:= http.DefaultClient.Do(req) 

    headerVal := res.Header.Get("Authorization") 

    fmt.Printf("auth header=%s, with length=%d\n", headerVal, len(headerVal)) 
    content, _ := ioutil.ReadAll(res.Body) 

    fmt.Printf("res.Body=%s", content) 
    res.Body.Close() 
} 

輸出到這個正在運行的代碼是:

auth header=, with length=0 
res.Body=map[Authorization:[responseAuthVal] User-Agent:[Go-http-client/1.1] Accept-Encoding:[gzip]] 

回答

6

這條線:

 r.Header.Set("Authorization", "responseAuthVal") 

設置值r *http.Request,即收到的請求,而您要設置值w http.ResponseWriter,即您將收到的響應。

上述行應

 w.Header().Set("Authorization", "responseAuthVal") 

this playgroud。

+0

哦,該死的,你說得對。非常感謝@Elwinar! – karysto

相關問題