package middleware import ( "pcgamedb/log" "strings" "time" "github.com/gin-gonic/gin" "go.uber.org/zap" ) func Logger() gin.HandlerFunc { return func(c *gin.Context) { startTime := time.Now() path := c.Request.URL.Path raw := c.Request.URL.RawQuery c.Next() if shouldSkipLog(path) { return } if raw != "" { path = path + "?" + raw } fields := []zap.Field{ zap.Int("status", c.Writer.Status()), zap.String("method", c.Request.Method), zap.String("path", path), zap.String("ip", getRealIP(c)), zap.Duration("latency", time.Since(startTime)), } if len(c.Errors) > 0 { fields = append(fields, zap.Strings("errors", c.Errors.Errors())) } log.Logger.Info("Request", fields...) } } func getRealIP(c *gin.Context) string { if ip := c.GetHeader("X-Real-IP"); ip != "" { return ip } if ip := c.GetHeader("X-Forwarded-For"); ip != "" { if index := strings.Index(ip, ","); index != -1 { return strings.TrimSpace(ip[:index]) } return ip } if ip := c.GetHeader("X-Originating-IP"); ip != "" { return ip } return c.ClientIP() } func shouldSkipLog(path string) bool { skipPaths := []string{ "/swagger/", "/favicon.ico", "/health", } for _, p := range skipPaths { if strings.HasPrefix(path, p) { return true } } return false }