1 Star 0 Fork 0

liujinsuo / tool

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
response_writer.go 1.36 KB
一键复制 编辑 原始数据 按行查看 历史
liujinsuo 提交于 2023-05-18 12:36 . ResponseWriter
package toolgin
import (
"bytes"
"github.com/gin-gonic/gin"
)
// Gin 框架在中间件中获取 response body 的方法
// https://www.toutiao.com/article/7182178685490004484/?wid=1684317766913
// ResponseWriter 自定义一个结构体,实现 gin.ResponseWriter interface
// 用于获取响应body,重写响应body。获取响应code,重写响应code
type ResponseWriter struct {
gin.ResponseWriter
body *bytes.Buffer
code int
}
// 重写 Write([]byte) (int, error) 方法
func (w *ResponseWriter) Write(b []byte) (int, error) {
return w.body.Write(b) //向一个bytes.buffer中写一份数据来为获取body使用
}
// WriteHeader 重写 WriteHeader(statusCode int) 方法
func (w *ResponseWriter) WriteHeader(statusCode int) {
w.code = statusCode //向一个code中写一份数据来为获取code使用
}
// GetBody 获取body
func (w *ResponseWriter) GetBody() *bytes.Buffer {
return w.body
}
// GetCode 获取code
func (w *ResponseWriter) GetCode() int {
return w.code
}
// CleanBody 清空body,可用与重写body
func (w *ResponseWriter) CleanBody() {
w.body = bytes.NewBuffer([]byte{})
}
// NewResponseWriter 包装 gin.ResponseWriter 接口
func NewResponseWriter(c *gin.Context) *ResponseWriter {
writer := ResponseWriter{
ResponseWriter: c.Writer,
body: bytes.NewBuffer([]byte{}),
code: 0,
}
c.Writer = &writer
return &writer
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/liujinsuo/tool.git
git@gitee.com:liujinsuo/tool.git
liujinsuo
tool
tool
c135d8583995

搜索帮助

344bd9b3 5694891 D2dac590 5694891