gpt4 book ai didi

http - Golang : Why does response. Get ("headerkey") 这段代码没有返回值?

转载 作者:IT王子 更新时间:2023-10-29 02:26:36 26 4
gpt4 key购买 nike

在过去的几个小时里,这一直困扰着我,我正在尝试获取响应 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com