当前位置 博文首页 > 解决Golang中ResponseWriter的一个坑

    解决Golang中ResponseWriter的一个坑

    作者:天地一小儒 时间:2021-06-02 18:08

    在使用Context.ResponseWriter中的Set/WriteHeader/Write这三个方法时,使用顺序必须如下所示,否则会出现某一设置不生效的情况。

    ctx.ResponseWriter.Header().Set("Content-type", "application/text")
     ctx.ResponseWriter.WriteHeader(403)
     ctx.ResponseWriter.Write([]byte(resp))

    如1:

    ctx.ResponseWriter.Header().Set("Content-type", "application/text")
     ctx.ResponseWriter.Write([]byte(resp))
     ctx.ResponseWriter.WriteHeader(403)
    

    会导致返回码一直是200

    补充:Go里w http.ResponseWriter,调用w.Write()方法报错

    Go里w http.ResponseWriter写入报错

    http: request method or response status code does not allow

    1. 下面是报错截图

    2. 点进去Write方法

    它首先是一个接口;

    由于它是在HTTP web服务器的应用场景,所以它具体的实现方法在net/http/server.go里:

    func (w *response) Write(data []byte) (n int, err error) {
     return w.write(len(data), data, "")
    }

    再点进去,函数里你会发现有一个关键的判断

    // 其中ErrBodyNotAllowed的
    // 代码内容
    // ErrBodyNotAllowed = errors.New("http: request method or response status code does not allow body")
    if !w.bodyAllowed() {
     return 0, ErrBodyNotAllowed
    }
     

    点进去,发现它在没有设置Header时会panic,当然这跟我们当前要讨论的问题关系不大,关键在bodyAllowedForStatus()方法

    func (w *response) bodyAllowed() bool {
     if !w.wroteHeader {
      panic("")
     }
     return bodyAllowedForStatus(w.status)
    }

    再点,终于看到了,当设置状态码为【100,199】、204、304就会报这个错,而我刚好设置的状态码就是204,我把它改成200重新试下,问题解决。

    func bodyAllowedForStatus(status int) bool {
     switch {
     case status >= 100 && status <= 199:
      return false
     case status == 204:
      return false
     case status == 304:
      return false
     }
     return true
    }

    以上为个人经验,希望能给大家一个参考,也希望大家多多支持站长博客。如有错误或未考虑完全的地方,望不吝赐教。

    js