Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

golang http response headers being removed

Tags:

go

I'm not sure if this is a bug or how the http response package is supposed to work.

In this example the Content-Type response header will not be set

// Return the response
w.WriteHeader(http.StatusCreated)
w.Header().Set("Content-Type", "application/json")
w.Write(js)

How ever if I flip the order of how the headers are set it does work:

// Return the response
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
w.Write(js)

Now this will actual set the header to application/json. Is this behavior intended?

like image 784
Rodrigo Avatar asked Sep 10 '16 15:09

Rodrigo


People also ask

Where do you go when you want to remove normal HTTP response headers?

Open the site which you would like to open and then click on the HTTP Response Headers option. Click on the X-Powered-By header and then click Remove on the Actions Pane to remove it from the response.

What are Httpheaders?

An HTTP header is a field of an HTTP request or response that passes additional context and metadata about the request or response. For example, a request message can use headers to indicate it's preferred media formats, while a response can use header to indicate the media format of the returned body.


1 Answers

Headers can only be written once to the response so you must set all the headers before writting them. Once the headers are written they are sent to the client.

You should only call w.WriteHeader(http.StatusCreated) once you have set all your headers.

Read in the GOLANG spec how WriteHeader works

This rule is the same for the body once the body is written (writting to the response is literally sending it to the client) it can not be resent or changed.

like image 113
dmportella Avatar answered Oct 15 '22 21:10

dmportella