作者热门文章
- r - 以节省内存的方式增长 data.frame
- ruby-on-rails - ruby/ruby on rails 内存泄漏检测
- android - 无法解析导入android.support.v7.app
- UNIX 域套接字与共享内存(映射文件)
在过去的几个小时里,这一直困扰着我,我正在尝试获取响应 header 值。简单的东西。如果我 curl
向这个正在运行的服务器发出请求,我会看到 header 集,带有 curl 的 -v
标志,但是当我尝试使用 Go 的 response 检索 header 时.Header.Get()
,显示空字符串""
,header的长度为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()
}
此运行代码的输出是:
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 Playground 。
关于http - Golang : Why does response. Get ("headerkey") 这段代码没有返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32454079/
有什么问题: 大量在线示例使用此值: http://www.coderanch.com/t/439139/Struts/wrong-select http://www.mkyong.com/stru
在过去的几个小时里,这一直困扰着我,我正在尝试获取响应 header 值。简单的东西。如果我 curl 向这个正在运行的服务器发出请求,我会看到 header 集,带有 curl 的 -v 标志,但是
我是一名优秀的程序员,十分优秀!