dongtao5104 2015-09-08 09:28
浏览 164
已采纳

Golang:为什么response.Get(“ headerkey”)在此代码中未返回值?

This has been bothering me for the past couple hours, I'm trying to get a response header value. Simple stuff. If I curl a request to this running server, I see the header set, with curl's -v flag, but when I try to retrieve the header using Go's response.Header.Get(), it shows a blank string "", with the header's length being 0.

What frustrates me even more, is that the header value is actually set within the response when I print out the body (as demonstrated below).

Any and all help with this is appreciated, thanks in advance.

I have this code here: http://play.golang.org/p/JaYTfVoDsq

Which contains the following:

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
", headerVal, len(headerVal))
    content, _ := ioutil.ReadAll(res.Body)

    fmt.Printf("res.Body=%s", content)
    res.Body.Close()
}

The output to this running code is:

auth header=, with length=0
res.Body=map[Authorization:[responseAuthVal] User-Agent:[Go-http-client/1.1] Accept-Encoding:[gzip]]
  • 写回答

1条回答 默认 最新

  • 普通网友 2015-09-08 09:39
    关注

    This line:

            r.Header.Set("Authorization", "responseAuthVal")
    

    set the value of r *http.Request, that is the incomming request, while you want to set the value of w http.ResponseWriter, the response that you will receive.

    The said line should be

            w.Header().Set("Authorization", "responseAuthVal")
    

    See this playgroud.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示