greg0ire
greg0ire

Reputation: 23255

Adding a header to a ResponseWriter

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.

Upvotes: 5

Views: 8561

Answers (1)

Itamar Lavender
Itamar Lavender

Reputation: 1028

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)
}

Upvotes: 18

Related Questions