添加一些注释
This commit is contained in:
+13
-6
@@ -4,6 +4,7 @@ import (
|
|||||||
"bytes"
|
"bytes"
|
||||||
"context"
|
"context"
|
||||||
"io"
|
"io"
|
||||||
|
"net/http"
|
||||||
|
|
||||||
"github.com/gin-gonic/gin"
|
"github.com/gin-gonic/gin"
|
||||||
uuid "github.com/satori/go.uuid"
|
uuid "github.com/satori/go.uuid"
|
||||||
@@ -19,25 +20,31 @@ func SetTradeId(ctx context.Context) context.Context {
|
|||||||
// 中间件 gin框架保存请求相关信息
|
// 中间件 gin框架保存请求相关信息
|
||||||
func MiddlewareGetGinParams(log *Logger) gin.HandlerFunc {
|
func MiddlewareGetGinParams(log *Logger) gin.HandlerFunc {
|
||||||
return func(ctx *gin.Context) {
|
return func(ctx *gin.Context) {
|
||||||
|
// 使用bytes.Buffer来读取并记录请求体,同时避免改变ctx.Request.Body
|
||||||
buf := &bytes.Buffer{}
|
buf := &bytes.Buffer{}
|
||||||
tea := io.TeeReader(ctx.Request.Body, buf)
|
tea := io.TeeReader(ctx.Request.Body, buf)
|
||||||
|
|
||||||
|
// 读取body
|
||||||
body, err := io.ReadAll(tea)
|
body, err := io.ReadAll(tea)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
// panic(err)
|
log.Infof(ctx, "Error reading request body: %v", err)
|
||||||
|
ctx.AbortWithStatus(http.StatusInternalServerError)
|
||||||
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// 截取body的前1000个字符
|
// 截取body的前1000个字符
|
||||||
bodys := string(body)
|
bodyStr := string(body)
|
||||||
if len(bodys) > 1000 {
|
if len(bodyStr) > 1000 {
|
||||||
bodys = bodys[:1000]
|
bodyStr = bodyStr[:1000]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 使用NopCloser包裹buffer,仅为了确保在读取body之后body可以被关闭,但并不改变原始的Request.Body
|
||||||
ctx.Request.Body = io.NopCloser(buf)
|
ctx.Request.Body = io.NopCloser(buf)
|
||||||
|
|
||||||
m := map[string]interface{}{
|
m := map[string]interface{}{
|
||||||
"method": ctx.Request.Method,
|
"method": ctx.Request.Method,
|
||||||
"uri": ctx.Request.RequestURI,
|
"uri": ctx.Request.RequestURI,
|
||||||
"body": bodys,
|
"body": bodyStr,
|
||||||
"query": ctx.Request.URL.Query(),
|
"query": ctx.Request.URL.Query(),
|
||||||
"header": ctx.Request.Header,
|
"header": ctx.Request.Header,
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user