登录
首页 >  Golang >  Go教程

解决Golang中ResponseWriter的一个坑

来源:脚本之家

时间:2022-12-23 18:04:56 112浏览 收藏

知识点掌握了,还需要不断练习才能熟练运用。下面golang学习网给大家带来一个Golang开发实战,手把手教大家学习《解决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. 下面是报错截图

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 

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

本篇关于《解决Golang中ResponseWriter的一个坑》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于Golang的相关知识,请关注golang学习网公众号!

声明:本文转载于:脚本之家 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>