为什么我不能为http重定向添加正文?

时间:2015-05-22 18:57:14

标签: http redirect go

这是我尝试过的:

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包?

2 个答案:

答案 0 :(得分:5)

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)
}

以上说明,在致电Header()Write()后,您无法更改WriteHeader()。您应该将代码更改为以下内容:

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

答案 1 :(得分:3)

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

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