Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a header to a ResponseWriter

Tags:

go

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.

like image 756
greg0ire Avatar asked Feb 06 '23 05:02

greg0ire


1 Answers

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)
}
like image 57
Itamar Lavender Avatar answered Feb 19 '23 18:02

Itamar Lavender