-
1、直接定义中间件
gopackage 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中使用中间件记录操作日志
水痕012023-09-07 10:57
相关推荐
车载中间件通信12 小时前
[TC8测试]TCP_FLAGS_PROCESSING_06kingx32 天前
网络安全事件应急响应:X集团 WebServer 入侵溯源与处置特立独行的猫a2 天前
ROS 2 主流DDS中间件入门:Cyclone DDS 与 Fast DDS 完全指南小易老师AI实战2 天前
用中间件把任务规划嵌进智能体循环绿蕉3 天前
从硬件内卷到“中间件荒“——仿真工具、开发接口、开源生态小易老师AI实战3 天前
LangGraph Agent 任务规划中间件:TodoListMiddleware 原理解析eleven_4u4 天前
QPS如何计算,如何部署架构喵了几个咪6 天前
GoWind ShortPlay 拆解:Ent privacy/viewer 多租户隔离——从中间件到 SQL 的零信任链qq_452396236 天前
第四篇:《索引原理与实战:B-tree、Hash、GIN、GiST、BRIN》ctlover6 天前
langchain 中间件