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()
}
}