Set up project files and add .gitignore to exclude local build/runtime artifacts. Made-with: Cursor
50 lines
958 B
Go
50 lines
958 B
Go
package middleware
|
|
|
|
import (
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"go.uber.org/zap"
|
|
)
|
|
|
|
// Logger 日志中间件
|
|
func Logger(logger *zap.Logger) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
start := time.Now()
|
|
path := c.Request.URL.Path
|
|
|
|
c.Next()
|
|
|
|
latency := time.Since(start)
|
|
statusCode := c.Writer.Status()
|
|
|
|
logger.Info("request",
|
|
zap.String("method", c.Request.Method),
|
|
zap.String("path", path),
|
|
zap.Int("status", statusCode),
|
|
zap.Duration("latency", latency),
|
|
zap.String("ip", c.ClientIP()),
|
|
zap.String("user-agent", c.Request.UserAgent()),
|
|
)
|
|
}
|
|
}
|
|
|
|
// Recovery 恢复中间件
|
|
func Recovery(logger *zap.Logger) gin.HandlerFunc {
|
|
return func(c *gin.Context) {
|
|
defer func() {
|
|
if err := recover(); err != nil {
|
|
logger.Error("panic recovered",
|
|
zap.Any("error", err),
|
|
)
|
|
c.JSON(500, gin.H{
|
|
"code": 500,
|
|
"message": "internal server error",
|
|
})
|
|
c.Abort()
|
|
}
|
|
}()
|
|
c.Next()
|
|
}
|
|
}
|