package middleware import ( "finance/backend/internal/logger" "net/http" "time" "github.com/gin-gonic/gin" ) // Logger is middleware for logging HTTP requests func Logger(log *logger.Logger) gin.HandlerFunc { return func(c *gin.Context) { // Start timer start := time.Now() // Process request c.Next() // Calculate latency latency := time.Since(start) // Log request log.LogRequest( c.Request.Method, c.Request.URL.Path, c.ClientIP(), c.Request.UserAgent(), c.Writer.Status(), latency, ) } } // ErrorHandler is middleware for handling errors func ErrorHandler(log *logger.Logger) gin.HandlerFunc { return func(c *gin.Context) { c.Next() // Handle errors after request is processed if len(c.Errors) > 0 { for _, e := range c.Errors { log.Error(e.Err) } // Return last error to client if response wasn't already sent if !c.Writer.Written() { c.JSON(http.StatusInternalServerError, gin.H{ "error": c.Errors.Last().Error(), }) } } } } // NotFoundHandler handles 404 errors func NotFoundHandler(c *gin.Context) { c.JSON(http.StatusNotFound, gin.H{ "error": "Resource not found", }) } // MethodNotAllowedHandler handles 405 errors func MethodNotAllowedHandler(c *gin.Context) { c.JSON(http.StatusMethodNotAllowed, gin.H{ "error": "Method not allowed", }) } // RecoveryWithLogger recovers from any panics and logs errors func RecoveryWithLogger(log *logger.Logger) gin.HandlerFunc { return func(c *gin.Context) { defer func() { if err := recover(); err != nil { log.Errorf("Panic recovered: %v", err) c.AbortWithStatusJSON(http.StatusInternalServerError, gin.H{ "error": "Internal server error", }) } }() c.Next() } }