Http 葛朗:为什么response.Get(“headerkey”)在这段代码中不返回值?
在过去的几个小时里,这一直困扰着我,我正在尝试获取一个响应头值。简单的东西。如果我Http 葛朗:为什么response.Get(“headerkey”)在这段代码中不返回值?,http,curl,go,header,Http,Curl,Go,Header,在过去的几个小时里,这一直困扰着我,我正在尝试获取一个响应头值。简单的东西。如果我curl请求此正在运行的服务器,我会看到标题集,带有curl的-v标志,但当我尝试使用Go的response.header.Get()检索标题时,它会显示一个空白字符串“”,标题长度为0 更让我沮丧的是,当我打印正文时,标题值实际上是在响应中设置的(如下所示) 在此方面的任何和所有帮助都将不胜感激,提前感谢 我这里有这个代码: 其中包含以下内容: package main import ( "fmt"
curl
请求此正在运行的服务器,我会看到标题集,带有curl的-v
标志,但当我尝试使用Go的response.header.Get()
检索标题时,它会显示一个空白字符串“”
,标题长度为0
更让我沮丧的是,当我打印正文时,标题值实际上是在响应中设置的(如下所示)
在此方面的任何和所有帮助都将不胜感激,提前感谢
我这里有这个代码:
其中包含以下内容:
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")
请参见PlayGround.这一行:
r.Header.Set("Authorization", "responseAuthVal")
设置r*http.Request
的值,即输入请求,同时要设置w http.ResponseWriter
的值,即您将收到的响应
这条线应该是
w.Header().Set("Authorization", "responseAuthVal")
参见playgroud