Files
photography/backend-old/internal/api/middleware/logger.go
xujiang 604b9e59ba fix
2025-07-10 18:09:11 +08:00

74 lines
1.7 KiB
Go
Raw 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 middleware
import (
"time"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
)
// LoggerMiddleware 日志中间件
func LoggerMiddleware(logger *zap.Logger) gin.HandlerFunc {
return func(c *gin.Context) {
start := time.Now()
path := c.Request.URL.Path
raw := c.Request.URL.RawQuery
// 处理请求
c.Next()
// 计算延迟
latency := time.Since(start)
// 获取请求信息
clientIP := c.ClientIP()
method := c.Request.Method
statusCode := c.Writer.Status()
bodySize := c.Writer.Size()
if raw != "" {
path = path + "?" + raw
}
// 记录日志
logger.Info("HTTP Request",
zap.String("method", method),
zap.String("path", path),
zap.String("client_ip", clientIP),
zap.Int("status_code", statusCode),
zap.Int("body_size", bodySize),
zap.Duration("latency", latency),
zap.String("user_agent", c.Request.UserAgent()),
)
}
}
// RequestIDMiddleware 请求ID中间件
func RequestIDMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
requestID := c.GetHeader("X-Request-ID")
if requestID == "" {
requestID = generateRequestID()
}
c.Set("request_id", requestID)
c.Header("X-Request-ID", requestID)
c.Next()
}
}
// generateRequestID 生成请求ID
func generateRequestID() string {
// 简单实现实际应用中可能需要更复杂的ID生成逻辑
return time.Now().Format("20060102150405") + "-" + randomString(8)
}
// randomString 生成随机字符串
func randomString(length int) string {
const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
b := make([]byte, length)
for i := range b {
b[i] = charset[time.Now().UnixNano()%int64(len(charset))]
}
return string(b)
}