英文:
golang http response headers being removed
问题
我不确定这是一个 bug 还是 http 响应包应该工作的方式。
在这个例子中,Content-Type
响应头将不会被设置:
// 返回响应
w.WriteHeader(http.StatusCreated)
w.Header().Set("Content-Type", "application/json")
w.Write(js)
然而,如果我改变头部设置的顺序,它就会起作用:
// 返回响应
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusCreated)
w.Write(js)
现在,这将实际设置头部为 application/json
。这个行为是有意的吗?
英文:
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
得分: 18
响应的头部只能写入一次,所以在写入之前必须设置好所有的头部信息。一旦头部被写入,它们就会被发送给客户端。
只有在设置好所有头部信息后,才应该调用w.WriteHeader(http.StatusCreated)
。
在 GOLANG 规范中阅读关于 WriteHeader 的工作原理
对于响应体来说,一旦写入(写入响应实际上是将其发送给客户端),就不能重新发送或更改。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论