daShangDao_centerBook/logging_middleware.go
2026-02-28 14:27:33 +08:00

55 lines
1.5 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package main
import (
"github.com/gin-gonic/gin"
"log"
"time"
)
// RequestAuditLogger 请求审计中间件。
// 作用为每个进入的请求记录方法、原始URI、匹配路由(endpoint)、状态码、客户端IP、UA、耗时等关键信息便于线上定位问题。
// 使用:在创建路由后通过 r.Use(RequestAuditLogger()) 注册。
func RequestAuditLogger() gin.HandlerFunc {
return func(c *gin.Context) {
start := time.Now()
c.Next()
endpoint := c.FullPath() // Gin 匹配到的路由模板;未匹配则为空字符串
if endpoint == "" {
endpoint = "<NoRoute>"
}
log.Printf(
"RequestAudit | %s %s | endpoint=%s | status=%d | ip=%s | ua=%s | cost=%v",
c.Request.Method,
c.Request.RequestURI,
endpoint,
c.Writer.Status(),
c.ClientIP(),
c.GetHeader("User-Agent"),
time.Since(start),
)
}
}
// NotFoundHandler 处理未匹配的路由。
// 作用:对 404 的请求进行详细记录,并返回结构化的提示信息,方便快速定位来源与路径。
// 使用:在路由注册完成后通过 r.NoRoute(NotFoundHandler) 注册。
func NotFoundHandler(c *gin.Context) {
log.Printf(
"NoRoute 404 | %s %s | ip=%s | ua=%s | referer=%s",
c.Request.Method,
c.Request.RequestURI,
c.ClientIP(),
c.GetHeader("User-Agent"),
c.GetHeader("Referer"),
)
c.JSON(404, gin.H{
"code": 404,
"msg": "接口不存在",
"method": c.Request.Method,
"path": c.Request.RequestURI,
"client_ip": c.ClientIP(),
})
}