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

标签 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 header 。
为什么golang的http包不能加body和重定向?

最佳答案

这记录在 net/http 中包裹:

type 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...')

关于http - 为什么我不能将正文添加到 http 重定向?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30404024/

相关文章:

http - 获取最后一页http请求golang

Android - 将编码图像 (1 - 2 MB) 上传到 base64 到服务器 HTTP POST - JSON

c# - ASP.NET MVC 在发送状态为 500 的响应时显示错误页面

regex - .htaccess : Removing unwanted symbols from the end of the URL

json - 如何将 header 添加到 JSON 以识别数组值的数组名称

json - 将 JSON 数组值映射到结构特定变量

http - Windows 8.1 更新 IIS 8.5 上的公共(public) HTTP 端口转发失败

apache - Htaccess 重定向 - 将许多规则合并到一个重定向中

javascript - 如何使用 Native Javascript 将 Ajax PHP 字符串重定向到新 URL?

multithreading - 在错误组中运行多个服务器的问题