I'm trying to set headers using golang and google app engine . Here's how the trivial code looks like:
w.Header().Set("Content-Type", "application/xml")
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("header-name", "value")
It seems that it's not working on my dev server. I always get the usual headers and
content-type:text/plain; charset=utf-8
When I deploy I get
Content-Type:text/html; charset=utf-8
Am I doing it wrong or this is a bug (another one)?
It seems the issue was that I set the http code before the custom headers. Be aware that if you have w.WriteHeader(200)
before w.Header
the headers will not be set.
There's definitely a bug with the GAE SDK. Unjustified different behaviour is observed between dev and prod environments. I am experiencing the same issue, where I set the headers at a specific order - works on dev but in prod headers are not set.
In dev env, this makes the headers you set return properly:
func SignalingHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
http.NotFound(w, r)
return
}
data := "test"
w.Write([]byte(data))
w.Header().Set("Content-Type", "application/json")
w.Header().Add("Access-Control-Allow-Origin", "*")
}
However in prod environment, I have to reverse the order - and use the "write" method only AFTER setting the headers (otherwise it won't work):
func SignalingHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
http.NotFound(w, r)
return
}
data := "test"
w.Header().Set("Content-Type", "application/json")
w.Header().Add("Access-Control-Allow-Origin", "*")
w.Write([]byte(data))
}
To make things work in prod, make sure you do not use the write method after setting any headers.
Without the rest of the code is hard to predict. However, the underlying reason is likely to be that you already wrote a response before setting the headers.
Either something like this:
w.Write([]byte(data))
Or something like this:
fmt.Printf(w, "A test response")