del*_*los 0 curl header http go
在过去的几个小时里,这一直困扰着我,我正在尝试获得响应标头值.简单的东西.如果我curl向这个正在运行的服务器发出请求,我会看到带有curl -v标志的标头集,但是当我尝试使用Go's检索标头时response.Header.Get(),它会显示一个空白字符串"",标题长度为0.
让我更沮丧的是,当我打印出身体时,标题值实际上是在响应中设置的(如下所示).
任何和所有的帮助,这是感谢,提前感谢.
我在这里有这个代码: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()
}
Run Code Online (Sandbox Code Playgroud)
此运行代码的输出是:
auth header=, with length=0
res.Body=map[Authorization:[responseAuthVal] User-Agent:[Go-http-client/1.1] Accept-Encoding:[gzip]]
Run Code Online (Sandbox Code Playgroud)
    这一行:
        r.Header.Set("Authorization", "responseAuthVal")
Run Code Online (Sandbox Code Playgroud)
设置值r *http.Request,即进入请求,同时设置w http.ResponseWriter您将收到的响应的值.
这条线应该是
        w.Header().Set("Authorization", "responseAuthVal")
Run Code Online (Sandbox Code Playgroud)
看到这个 playgroud.