dounei9043 2015-05-22 18:57
浏览 51
已采纳

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

Here is what I've tried:

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

It won't add the Location header for some odd reason.
Why isn't it possible to add a body and redirect golang's http package?

  • 写回答

2条回答 默认 最新

  • du5591 2015-05-22 19:01
    关注

    This is documented in the net/http package:

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

    The above states that you cannot change Header() after a call to Write() or WriteHeader(). You should change your code to the following:

    w.Header().Set("Location", "/myredirecturl")
    w.WriteHeader(301)
    w.Write('Redirecting...')
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 请看一下,学校实验要求,我需要具体代码
  • ¥50 pc微信3.6.0.18不能登陆 有偿解决问题
  • ¥20 MATLAB绘制两隐函数曲面的交线
  • ¥15 求TYPCE母转母转接头24PIN线路板图
  • ¥100 国外网络搭建,有偿交流
  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃