I'm trying to contribute a fix for this issue, and tried something similar to this, but no matter what header I try to set, I don't see it in the http response I am trying to modify.
This is the method I'm trying to change, and here is the line I tried to add :
w.Header().Set("Content-Type", "application/json")
.
The full method :
func (s *HTTPServer) getServices(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(s.list.GetAllServices()); err != nil {
log.Println("Error encoding: ", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
I would expect the header to change, but it always is text/plain; charset=utf-8
Disclaimer: this is the first piece of code I wrote (or rather, copy/pasted/adapted) in Go.
if somebody hit this issue, the next info might be helpful.
the reason this wasn't working is the status code was written out before the attempt to add the content-type header.
to make it work, all headers should be added before w.WriteHeader(status code) is being invoked. example:
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
encoder := json.NewEncoder(w)
encoder.SetEscapeHTML(false)
if err := encoder.Encode(s.list.GetAllServices()); err != nil {
panic(err)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With