golang http response headers being removed

时间:2016-09-10 15:24:21

标签: 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?

1 个答案:

答案 0 :(得分:13)

标题只能写入一次,因此您必须在写入之前设置所有标题。一旦标题被写入,它们就会被发送到客户端。

只有在设置了所有标题后,才应致电w.WriteHeader(http.StatusCreated)

Read in the GOLANG spec how WriteHeader works

一旦写入正文,这个规则对于正文来说是相同的(写入响应的字面意思是将其发送给客户端)它不能重新发送或更改。