【问题标题】:golang http response headers being removedgolang http响应标头被删除
【发布时间】:2017-01-18 13:08:02
【问题描述】:

我不确定这是否是一个错误或 http 响应包应该如何工作。

在本例中,Content-Type 响应标头不会被设置

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

如果我颠倒标题设置的顺序,它会起作用:

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

现在这会将标题设置为application/json。这种行为是有意的吗?

【问题讨论】:

    标签: go


    【解决方案1】:

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

    您只应在设置完所有标题后调用w.WriteHeader(http.StatusCreated)

    Read in the GOLANG spec how WriteHeader works

    这个规则对于正文是一样的,一旦正文被写入(写入响应实际上就是将其发送给客户端),它就不能被重新发送或更改。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-15
      • 2013-04-26
      • 2018-07-07
      • 2013-12-09
      • 2011-02-13
      • 1970-01-01
      • 1970-01-01
      • 2011-07-05
      相关资源
      最近更新 更多