上一篇文章《Golang gin 框架在中间件中获取请求和响应的各种数据》介绍了在 gin 框架中间件中获取各种数据的方法,其实 echo 框架也大体类似,只是获取 request body 和 response body 的方式有些不同,接下来就直接使用代码来演示一下在 echo 框架中间件中的获取方法:
package main
import (
"bytes""fmt""github.com/labstack/echo/v4""io""log""net/http"
)
funcmain() {
e := echo.New()
e.Use(Test())
e.POST("/test", func(c echo.Context)error {
return c.JSON(200, map[string]interface{}{"code": 1, "data": "test data", "msg": ""})
})
log.Fatal(e.Start(":8080"))
}
type bodyDumpResponseWriter struct {
io.Writer
http.ResponseWriter
}
func(w *bodyDumpResponseWriter)Write(b []byte)(int, error) {
return w.Writer.Write(b)
}
funcTest()echo.MiddlewareFunc {
returnfunc(next echo.HandlerFunc)echo.HandlerFunc {
returnfunc(c echo.Context)error {
//获取 request body
requestBody := ""
b, err := io.ReadAll(c.Request().Body)
if err != nil {
requestBody = "failed to get request body"
} else {
requestBody = string(b)
c.Request().Body = io.NopCloser(bytes.NewBuffer(b))
}
//获取 response body
resBody := new(bytes.Buffer)
mw := io.MultiWriter(c.Response().Writer, resBody)
writer := &bodyDumpResponseWriter{Writer: mw, ResponseWriter: c.Response().Writer}
c.Response().Writer = writer
deferfunc() {
fmt.Printf("request body: %s, response body: %s \n", requestBody, resBody.String())
}()
//获取 response bodyreturn next(c)
}
}
}
运行程序后,在命令行工具里面使用curl访问接口(也可以使用postman等工具):
curl 'http://localhost:8080/test' \
-H "Content-Type:application/json" \
-X POST \
-d '{"name":"xiaoming"}'
查看控制台打印结果,如下:
request body: {"name":"xiaoming"}, response body: {"code":1,"data":"test data","msg":""}
可以看到成功获取到了 request body 和 response body。