Reputation: 3341
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\n", 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]]
Upvotes: 0
Views: 1424
Reputation: 9509
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.
Upvotes: 6