网络编程
位置:首页>> 网络编程>> Go语言>> 解决Golang中ResponseWriter的一个坑

解决Golang中ResponseWriter的一个坑

作者:天地一小儒  发布时间:2024-04-25 15:11:43 

标签:Golang,ResponseWriter

在使用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. 下面是报错截图

解决Golang中ResponseWriter的一个坑

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
}

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

来源:https://blog.csdn.net/u012107512/article/details/80691423

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com