Golang的HTTP响应头被移除了。

huangapple go评论69阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2016年9月10日 23:24:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/39427544.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定