- 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() //请求ip 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) } } // TODO 插入到数据库中 } // 打印日志 //loggerMap := map[string]interface{} { // "status_code":statusCode, // "client_ip": clientIP, // "req_method":method, // "req_uri": reqUrl, //} //marshal, _ := json.Marshal(loggerMap) 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() } }
- 2、在需要使用的地方直接使用就可以,自动会收集日志到数据库中
简单记录下gin中使用中间件记录操作日志
最新推荐文章于 2024-12-27 18:06:35 发布