【问题标题】:Why can't I add a body to an http redirect?为什么我不能将正文添加到 http 重定向?
【发布时间】:2015-08-04 21:48:50
【问题描述】:

这是我尝试过的:

w.WriteHeader(301)
w.Write([]byte("Redirecting..."))
w.Header().Set("Location", "/myredirecturl")
w.Header().Set("Content-Length", contentLength) // I thought this might help

由于某些奇怪的原因,它不会添加 Location 标头。
golang的http包为什么不能加body重定向?

【问题讨论】:

  • 为什么要在重定向中设置正文?客户可能会忽略正文,只关注Location
  • @LutzHorn,例如请参阅带有 301 和正文的 Wikipedia example
  • 另请注意,http.Redirect 遵循putting a simple body for GET requests 的 RFC2616 建议。如果这就是你所需要的,你可以打电话给它;或者您可以查看源代码以使用自定义正文滚动您自己的版本。
  • @DaveC,是的,我阅读了 RFC 的那部分,并且看到了 go 实现,但我需要一个带有重定向的自定义正文。

标签: http redirect go


【解决方案1】:

这在net/http 包中有记录:

类型 ResponseWriter

type ResponseWriter interface {
    // Header returns the header map that will be sent by WriteHeader.
    // Changing the header after a call to WriteHeader (or Write) has
    // no effect.
    Header() Header

    // Write writes the data to the connection as part of an HTTP reply.
    // If WriteHeader has not yet been called, Write calls WriteHeader(http.StatusOK)
    // before writing the data.  If the Header does not contain a
    // Content-Type line, Write adds a Content-Type set to the result of passing
    // the initial 512 bytes of written data to DetectContentType.
    Write([]byte) (int, error)

    // WriteHeader sends an HTTP response header with status code.
    // If WriteHeader is not called explicitly, the first call to Write
    // will trigger an implicit WriteHeader(http.StatusOK).
    // Thus explicit calls to WriteHeader are mainly used to
    // send error codes.
    WriteHeader(int)
}

上述声明在调用Write()WriteHeader() 后无法更改Header()。您应该将代码更改为以下内容:

w.Header().Set("Location", "/myredirecturl")
w.WriteHeader(301)
w.Write('Redirecting...')

【讨论】:

  • 谢谢!但是,如果您在 chrome 上对此进行测试并查看“网络”窗格,则 chrome 不会显示任何正文:\(它会输出:“无法加载响应数据”)
  • @funerr play.golang.org/p/CPWIVR0_sk 适用于 Firefox,但我认为它是否显示正文或只是安静地跟随重定向取决于浏览器(以及附加组件和设置)。
【解决方案2】:

问题在于,一旦您调用 Write 或 WriteHeader,标头就会被刷新到客户端。此后设置的任何标头都将被忽略。所以只要改变命令的顺序就可以解决这个问题:

w.Header().Set("Location", "/myredirecturl")
w.Header().Set("Content-Length", contentLength) // I thought this might 
w.WriteHeader(301)
w.Write('Redirecting...')

【讨论】:

  • 就像我在蒂姆的回答中评论的那样,当我查看重定向响应时,正文未显示在 chrome 网络中。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-07-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-19
  • 2011-01-30
  • 2018-12-02
  • 1970-01-01
相关资源
最近更新 更多