1、直接定义中间件package middleware
import (
"bytes"
"encoding/json"
"fmt"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
"io"
"strconv"
"strings"
)
func LoggerMiddleWare() gin.HandlerFunc {
return func(ctx *gin.Context) {
method := ctx.Request.Method
reqUrlList := strings.Split(ctx.Request.URL.String(), "?")
statusCode := ctx.Writer.Status()
clientIP := ctx.ClientIP()
var data map[string]interface{}
body, err := io.ReadAll(ctx.Request.Body)
ctx.Request.Body = io.NopCloser(bytes.NewBuffer(body))
if err != nil {
fmt.Println(err, "????")
}
err = json.Unmarshal(body, &data)
if reqUrlList[0] != "/api/v1/admin/login" {
message := ""
if method == "GET" {
if len(reqUrlList) == 2 && reqUrlList[1] != "" {
message = reqUrlList[1]
}
} else {
if utils.MapToJson(data) != "null" {
message = utils.MapToJson(data)
}
}
}
loggerStr := fmt.Sprintf("status_code:%s,client_ip:%s,req_method:%s,req_uri:%s", strconv.Itoa(statusCode), clientIP, method, reqUrlList[0])
global.Logger.Info("中间件本次请求", zap.String("http", loggerStr))
ctx.Next()
}
}

- 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
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61