Golang:为什么 response.Get("headerkey") 不是 return 这段代码中的值?
Golang: Why does response.Get("headerkey") not return a value in this code?
过去几个小时这一直困扰着我,我正在尝试获得响应 header 值。简单的东西。如果我 curl
向这个 运行 服务器发出请求,我会看到 header 设置,带有 curl 的 -v
标志,但是当我尝试检索 header 使用Go的response.Header.Get()
,显示的是空字符串""
,header的长度为0。
更让我沮丧的是,当我打印出 body(如下所示)时,header 值实际上是在响应中设置的。
在此先感谢您提供的任何帮助。
我这里有这段代码:
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]]
这一行:
r.Header.Set("Authorization", "responseAuthVal")
设置r *http.Request
的值,即传入请求,而你想设置w http.ResponseWriter
的值,你将收到的响应。
上述行应该是
w.Header().Set("Authorization", "responseAuthVal")
参见this游乐场。
过去几个小时这一直困扰着我,我正在尝试获得响应 header 值。简单的东西。如果我 curl
向这个 运行 服务器发出请求,我会看到 header 设置,带有 curl 的 -v
标志,但是当我尝试检索 header 使用Go的response.Header.Get()
,显示的是空字符串""
,header的长度为0。
更让我沮丧的是,当我打印出 body(如下所示)时,header 值实际上是在响应中设置的。
在此先感谢您提供的任何帮助。
我这里有这段代码: 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]]
这一行:
r.Header.Set("Authorization", "responseAuthVal")
设置r *http.Request
的值,即传入请求,而你想设置w http.ResponseWriter
的值,你将收到的响应。
上述行应该是
w.Header().Set("Authorization", "responseAuthVal")
参见this游乐场。