【笔记】Gin中间件获取响应体数据

前言

Gin中间件获取响应体数据

正文

  • 这种操作只能获取响应体数据的内容,并不能强制修改响应体数据的内容
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// 继承ResponseWriter
type getResponseBody struct {
gin.ResponseWriter
body *bytes.Buffer
}

// 重写Write()方法
func (res getResponseBody) Write(b []byte) (int, error) {
res.body.Write(b)
return res.ResponseWriter.Write(b)
}

func deleteResponseDataNullValue() gin.HandlerFunc {
return func(context *gin.Context) {
// 将改写的ResponseWriter替换Gin的ResponseWriter
var response = &getResponseBody{
ResponseWriter: context.Writer,
body: bytes.NewBufferString(""),
}
context.Writer = response
// 执行业务操作
context.Next()
// 得到响应状态
statusCode := context.Writer.Status()
if statusCode == http.StatusOK {
// 获取响应体数据
var body = response.body.String()
}
}
}

完成

参考文献

CSDN——wilson_go