diff options
author | 2025-04-25 03:07:37 +0530 | |
---|---|---|
committer | 2025-04-25 03:07:37 +0530 | |
commit | 7b9fe4639cafbcc35c860e23a20a2c0d2e29283d (patch) | |
tree | eef9b87745ed5e9b90f842c004941d12d705e7ac | |
parent | d8856efd30dfcb05b26a5b66b5bb14cc0604e2b1 (diff) | |
download | finance-7b9fe4639cafbcc35c860e23a20a2c0d2e29283d.tar.gz finance-7b9fe4639cafbcc35c860e23a20a2c0d2e29283d.tar.bz2 finance-7b9fe4639cafbcc35c860e23a20a2c0d2e29283d.zip |
finance/backend: feat: set up logging and error handling
-rw-r--r-- | README.md | 2 | ||||
-rw-r--r-- | backend/cmd/api/main.go | 215 | ||||
-rw-r--r-- | backend/handlers/goal_handler.go | 25 | ||||
-rw-r--r-- | backend/internal/config/config.go | 88 | ||||
-rw-r--r-- | backend/internal/logger/logger.go | 144 | ||||
-rw-r--r-- | backend/internal/middleware/error_handler.go | 119 | ||||
-rw-r--r-- | backend/middleware/middleware.go | 83 |
7 files changed, 533 insertions, 143 deletions
@@ -91,7 +91,7 @@ An application designed to help manage personal finances, including income (like * [x] Create basic CRUD APIs for Transactions (Income, Expense) * [x] Create basic CRUD APIs for Loans * [x] Create basic CRUD APIs for Goals -* [ ] Set up initial logging and error handling +* [x] Set up initial logging and error handling * [ ] Write unit/integration tests for core API endpoints **Phase 2: Frontend Foundation (React/Next.js + shadcn/ui)** diff --git a/backend/cmd/api/main.go b/backend/cmd/api/main.go index e1d0824..f882175 100644 --- a/backend/cmd/api/main.go +++ b/backend/cmd/api/main.go @@ -1,40 +1,77 @@ package main import ( - "log" + "fmt" "net/http" + "os" "time" - "finance/backend/internal/api/auth" - "finance/backend/internal/api/v1/accounts" - "finance/backend/internal/api/v1/goals" - "finance/backend/internal/api/v1/loans" - "finance/backend/internal/api/v1/transactions" + "finance/backend/handlers" "finance/backend/internal/config" "finance/backend/internal/database" + "finance/backend/internal/logger" + "finance/backend/internal/middleware" + "finance/backend/internal/models" "github.com/gin-contrib/cors" "github.com/gin-gonic/gin" ) func main() { - // Load Configuration + // Initialize logger + log := logger.NewLogger(os.Stdout, logger.INFO) + log.Info("Starting API server...") + + // Load configuration cfg, err := config.LoadConfig() if err != nil { - log.Fatalf("Failed to load configuration: %v", err) + log.Fatal("Failed to load configuration:", err) + } + + // Set Gin mode based on environment + if cfg.Environment == "production" { + gin.SetMode(gin.ReleaseMode) + } else { + gin.SetMode(gin.DebugMode) + } + + // Initialize database + err = database.InitDatabase(cfg) + if err != nil { + log.Fatal("Failed to connect to database:", err) } - // Initialize Database - if err := database.InitDatabase(cfg); err != nil { - log.Fatalf("Failed to initialize database: %v", err) + // Auto migrate database models + err = database.DB.AutoMigrate( + &models.User{}, + &models.Account{}, + &models.Transaction{}, + &models.Goal{}, + &models.Loan{}, + ) + if err != nil { + log.Fatal("Failed to migrate database:", err) } - // Setup Gin Router - r := gin.Default() + // Initialize handlers + goalHandler := handlers.NewGoalHandler() + // Initialize other handlers as needed + // userHandler := handlers.NewUserHandler() + // accountHandler := handlers.NewAccountHandler() + // transactionHandler := handlers.NewTransactionHandler() + // loanHandler := handlers.NewLoanHandler() + // authHandler := handlers.NewAuthHandler() + + // Create a new Gin router without default middleware + r := gin.New() + + // Add custom middleware + r.Use(middleware.RequestLogger(log)) + r.Use(middleware.ErrorHandler()) // Configure CORS r.Use(cors.New(cors.Config{ - AllowOrigins: []string{"http://localhost:3000"}, + AllowOrigins: []string{"*"}, AllowMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"}, AllowHeaders: []string{"Origin", "Content-Type", "Accept", "Authorization"}, ExposeHeaders: []string{"Content-Length"}, @@ -42,115 +79,77 @@ func main() { MaxAge: 12 * time.Hour, })) + // Set up custom handlers for 404 and 405 + r.NoRoute(middleware.NotFoundHandler()) + r.NoMethod(middleware.MethodNotAllowedHandler()) + // Public utility endpoints - r.GET("/ping", func(c *gin.Context) { - c.JSON(http.StatusOK, gin.H{ - "message": "pong", - }) + r.GET("/health", func(c *gin.Context) { + c.JSON(http.StatusOK, gin.H{"status": "ok", "timestamp": time.Now().Unix()}) }) - // Add database status endpoint - r.GET("/db-status", func(c *gin.Context) { - // Try to get a connection from the pool + r.GET("/dbstatus", func(c *gin.Context) { sqlDB, err := database.DB.DB() if err != nil { - c.JSON(http.StatusInternalServerError, gin.H{ - "status": "error", - "message": "Failed to get database connection", - "error": err.Error(), - }) + c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "message": "Database connection error"}) return } - - // Check if database is reachable err = sqlDB.Ping() if err != nil { - c.JSON(http.StatusInternalServerError, gin.H{ - "status": "error", - "message": "Database is not reachable", - "error": err.Error(), - }) + c.JSON(http.StatusInternalServerError, gin.H{"status": "error", "message": "Database ping failed"}) return } - - c.JSON(http.StatusOK, gin.H{ - "status": "success", - "message": "Database connection is healthy", - }) + c.JSON(http.StatusOK, gin.H{"status": "ok", "message": "Database connection is healthy"}) }) // API v1 routes v1 := r.Group("/api/v1") - { - // Auth routes (public) - v1.POST("/auth/signup", auth.Signup(cfg)) - v1.POST("/auth/login", auth.Login(cfg)) - - // Protected routes - protected := v1.Group("") - protected.Use(auth.AuthMiddleware(cfg)) - { - // User routes - protected.GET("/users/me", func(c *gin.Context) { - // Get user from context (set by auth middleware) - user, exists := c.Get("user") - if !exists { - c.JSON(http.StatusNotFound, gin.H{"error": "User not found"}) - return - } - - c.JSON(http.StatusOK, gin.H{"user": user}) - }) - - // Account routes - accountRoutes := protected.Group("/accounts") - { - accountRoutes.GET("", accounts.GetAccounts()) - accountRoutes.GET("/:id", accounts.GetAccountByID()) - accountRoutes.POST("", accounts.CreateAccount()) - accountRoutes.PUT("/:id", accounts.UpdateAccount()) - accountRoutes.DELETE("/:id", accounts.DeleteAccount()) - } - - // Transaction routes - transactionRoutes := protected.Group("/transactions") - { - transactionRoutes.GET("", transactions.GetTransactions()) - transactionRoutes.GET("/:id", transactions.GetTransactionByID()) - transactionRoutes.POST("", transactions.CreateTransaction()) - transactionRoutes.PUT("/:id", transactions.UpdateTransaction()) - transactionRoutes.DELETE("/:id", transactions.DeleteTransaction()) - } - - // Goal routes - goalRoutes := protected.Group("/goals") - { - goalRoutes.GET("", goals.GetGoals()) - goalRoutes.GET("/:id", goals.GetGoalByID()) - goalRoutes.POST("", goals.CreateGoal()) - goalRoutes.PUT("/:id", goals.UpdateGoal()) - goalRoutes.DELETE("/:id", goals.DeleteGoal()) - goalRoutes.PATCH("/:id/progress", goals.UpdateGoalProgress()) // Specific endpoint for updating progress - } - - // Loan routes - loanRoutes := protected.Group("/loans") - { - loanRoutes.GET("", loans.GetLoans()) - loanRoutes.GET("/:id", loans.GetLoanByID()) - loanRoutes.POST("", loans.CreateLoan()) - loanRoutes.PUT("/:id", loans.UpdateLoan()) - loanRoutes.DELETE("/:id", loans.DeleteLoan()) - } - } - } - // Run the server - serverAddr := ":8080" // TODO: Make this configurable via cfg - log.Printf("Starting server on %s", serverAddr) - err = r.Run(serverAddr) - if err != nil { - // Use Fatalf to exit if server fails to start - log.Fatalf("Failed to start server: %v", err) + // Authentication routes (no JWT required) + // v1.POST("/register", authHandler.Register) + // v1.POST("/login", authHandler.Login) + + // Protected routes (JWT required) + protected := v1.Group("") + // protected.Use(authHandler.JWTAuth) + + // User routes + // protected.GET("/users/me", userHandler.GetCurrentUser) + // protected.PUT("/users/me", userHandler.UpdateCurrentUser) + + // Account routes + // protected.GET("/accounts", accountHandler.GetAccounts) + // protected.GET("/accounts/:id", accountHandler.GetAccountByID) + // protected.POST("/accounts", accountHandler.CreateAccount) + // protected.PUT("/accounts/:id", accountHandler.UpdateAccount) + // protected.DELETE("/accounts/:id", accountHandler.DeleteAccount) + + // Transaction routes + // protected.GET("/transactions", transactionHandler.GetTransactions) + // protected.GET("/transactions/:id", transactionHandler.GetTransactionByID) + // protected.POST("/transactions", transactionHandler.CreateTransaction) + // protected.PUT("/transactions/:id", transactionHandler.UpdateTransaction) + // protected.DELETE("/transactions/:id", transactionHandler.DeleteTransaction) + + // Goal routes + protected.GET("/goals", goalHandler.GetGoals) + protected.GET("/goals/:id", goalHandler.GetGoal) + protected.POST("/goals", goalHandler.CreateGoal) + protected.PUT("/goals/:id", goalHandler.UpdateGoal) + protected.DELETE("/goals/:id", goalHandler.DeleteGoal) + protected.PATCH("/goals/:id/progress", goalHandler.UpdateGoalProgress) + + // Loan routes + // protected.GET("/loans", loanHandler.GetLoans) + // protected.GET("/loans/:id", loanHandler.GetLoanByID) + // protected.POST("/loans", loanHandler.CreateLoan) + // protected.PUT("/loans/:id", loanHandler.UpdateLoan) + // protected.DELETE("/loans/:id", loanHandler.DeleteLoan) + + // Start server + serverAddr := fmt.Sprintf("%s:%d", cfg.ServerHost, cfg.ServerPort) + log.Info("Server starting on", serverAddr) + if err := r.Run(serverAddr); err != nil { + log.Fatal("Server failed to start:", err) } } diff --git a/backend/handlers/goal_handler.go b/backend/handlers/goal_handler.go index dd2791c..53a3d6e 100644 --- a/backend/handlers/goal_handler.go +++ b/backend/handlers/goal_handler.go @@ -1,6 +1,7 @@ package handlers import ( + "log" "net/http" "strconv" "time" @@ -54,6 +55,7 @@ func (h *GoalHandler) GetGoals(c *gin.Context) { } if err := query.Find(&goals).Error; err != nil { + log.Printf("Error fetching goals for user %d: %v", userID, err) c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to get goals"}) return } @@ -66,12 +68,14 @@ func (h *GoalHandler) GetGoal(c *gin.Context) { userID := c.MustGet("userID").(uint) goalID, err := strconv.ParseUint(c.Param("id"), 10, 32) if err != nil { + log.Printf("Error parsing goal ID: %v", err) c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid goal ID"}) return } var goal models.Goal if err := database.DB.Where("id = ? AND user_id = ?", goalID, userID).First(&goal).Error; err != nil { + log.Printf("Error fetching goal ID %d for user %d: %v", goalID, userID, err) c.JSON(http.StatusNotFound, gin.H{"error": "Goal not found"}) return } @@ -85,6 +89,7 @@ func (h *GoalHandler) CreateGoal(c *gin.Context) { var input CreateGoalInput if err := c.ShouldBindJSON(&input); err != nil { + log.Printf("Error binding JSON for goal creation: %v", err) c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } @@ -100,6 +105,7 @@ func (h *GoalHandler) CreateGoal(c *gin.Context) { if input.TargetDate != "" { parsedDate, err := time.Parse("2006-01-02", input.TargetDate) if err != nil { + log.Printf("Error parsing target date for goal creation: %v", err) c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid date format for targetDate. Use YYYY-MM-DD"}) return } @@ -120,10 +126,12 @@ func (h *GoalHandler) CreateGoal(c *gin.Context) { } if err := database.DB.Create(&goal).Error; err != nil { + log.Printf("Error creating goal for user %d: %v", userID, err) c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to create goal"}) return } + log.Printf("Goal created successfully for user %d: %s (ID: %d)", userID, goal.Name, goal.ID) c.JSON(http.StatusCreated, goal) } @@ -132,18 +140,21 @@ func (h *GoalHandler) UpdateGoal(c *gin.Context) { userID := c.MustGet("userID").(uint) goalID, err := strconv.ParseUint(c.Param("id"), 10, 32) if err != nil { + log.Printf("Error parsing goal ID for update: %v", err) c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid goal ID"}) return } var goal models.Goal if err := database.DB.Where("id = ? AND user_id = ?", goalID, userID).First(&goal).Error; err != nil { + log.Printf("Error fetching goal ID %d for user %d in update: %v", goalID, userID, err) c.JSON(http.StatusNotFound, gin.H{"error": "Goal not found"}) return } var input UpdateGoalInput if err := c.ShouldBindJSON(&input); err != nil { + log.Printf("Error binding JSON for goal update: %v", err) c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } @@ -161,6 +172,7 @@ func (h *GoalHandler) UpdateGoal(c *gin.Context) { if input.TargetDate != "" { parsedDate, err := time.Parse("2006-01-02", input.TargetDate) if err != nil { + log.Printf("Error parsing target date for goal update: %v", err) c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid date format for targetDate. Use YYYY-MM-DD"}) return } @@ -173,13 +185,16 @@ func (h *GoalHandler) UpdateGoal(c *gin.Context) { // Check if goal has been achieved if goal.CurrentAmount >= goal.TargetAmount { goal.Status = "Achieved" + log.Printf("Goal ID %d for user %d automatically marked as Achieved", goalID, userID) } if err := database.DB.Save(&goal).Error; err != nil { + log.Printf("Error saving updated goal ID %d for user %d: %v", goalID, userID, err) c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to update goal"}) return } + log.Printf("Goal ID %d updated successfully for user %d", goalID, userID) c.JSON(http.StatusOK, goal) } @@ -188,18 +203,21 @@ func (h *GoalHandler) UpdateGoalProgress(c *gin.Context) { userID := c.MustGet("userID").(uint) goalID, err := strconv.ParseUint(c.Param("id"), 10, 32) if err != nil { + log.Printf("Error parsing goal ID for progress update: %v", err) c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid goal ID"}) return } var goal models.Goal if err := database.DB.Where("id = ? AND user_id = ?", goalID, userID).First(&goal).Error; err != nil { + log.Printf("Error fetching goal ID %d for user %d in progress update: %v", goalID, userID, err) c.JSON(http.StatusNotFound, gin.H{"error": "Goal not found"}) return } var input UpdateGoalProgressInput if err := c.ShouldBindJSON(&input); err != nil { + log.Printf("Error binding JSON for goal progress update: %v", err) c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } @@ -209,13 +227,16 @@ func (h *GoalHandler) UpdateGoalProgress(c *gin.Context) { // Check if goal has been achieved if goal.CurrentAmount >= goal.TargetAmount { goal.Status = "Achieved" + log.Printf("Goal ID %d for user %d automatically marked as Achieved during progress update", goalID, userID) } if err := database.DB.Save(&goal).Error; err != nil { + log.Printf("Error saving progress update for goal ID %d for user %d: %v", goalID, userID, err) c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to update goal progress"}) return } + log.Printf("Goal ID %d progress updated successfully for user %d: %d/%d", goalID, userID, goal.CurrentAmount, goal.TargetAmount) c.JSON(http.StatusOK, goal) } @@ -224,20 +245,24 @@ func (h *GoalHandler) DeleteGoal(c *gin.Context) { userID := c.MustGet("userID").(uint) goalID, err := strconv.ParseUint(c.Param("id"), 10, 32) if err != nil { + log.Printf("Error parsing goal ID for deletion: %v", err) c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid goal ID"}) return } var goal models.Goal if err := database.DB.Where("id = ? AND user_id = ?", goalID, userID).First(&goal).Error; err != nil { + log.Printf("Error fetching goal ID %d for user %d for deletion: %v", goalID, userID, err) c.JSON(http.StatusNotFound, gin.H{"error": "Goal not found"}) return } if err := database.DB.Delete(&goal).Error; err != nil { + log.Printf("Error deleting goal ID %d for user %d: %v", goalID, userID, err) c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to delete goal"}) return } + log.Printf("Goal ID %d deleted successfully for user %d", goalID, userID) c.JSON(http.StatusOK, gin.H{"message": "Goal deleted successfully"}) } diff --git a/backend/internal/config/config.go b/backend/internal/config/config.go index f61f423..f302827 100644 --- a/backend/internal/config/config.go +++ b/backend/internal/config/config.go @@ -1,54 +1,74 @@ package config import ( - "log" + "fmt" "os" "github.com/joho/godotenv" ) -// Config holds the application configuration +// Config holds application configuration type Config struct { + // Database configuration DatabaseDSN string - JWTSecret string // Secret key for signing JWTs - // Add other config fields here later (e.g., server port) + + // JWT configuration + JWTSecret string + JWTExpiry int // in hours + + // Server configuration + ServerPort int + ServerHost string + + // Environment (development, staging, production) + Environment string } -// LoadConfig loads configuration from environment variables or a .env file +// LoadConfig loads the application configuration from environment variables func LoadConfig() (*Config, error) { - // Attempt to load .env file (useful for development) - // In production, rely on environment variables set directly - err := godotenv.Load() // Load .env file from current directory or parent dirs - if err != nil { - log.Println("No .env file found, relying on environment variables") + // Load .env file if it exists + _ = godotenv.Load() // Ignore error if .env file doesn't exist + + // Set defaults and override with environment variables + config := &Config{ + DatabaseDSN: getEnv("DATABASE_DSN", "postgresql://postgres:postgres@localhost:5432/finance?sslmode=disable"), + JWTSecret: getEnv("JWT_SECRET", "supersecretkey"), // This should be changed in production + JWTExpiry: getEnvInt("JWT_EXPIRY", 24), // Default to 24 hours + ServerPort: getEnvInt("SERVER_PORT", 8080), // Default to 8080 + ServerHost: getEnv("SERVER_HOST", "0.0.0.0"), // Default to all interfaces + Environment: getEnv("APP_ENV", "development"), // Default to development } - dsn := os.Getenv("DATABASE_DSN") - if dsn == "" { - // Set a default for local development if not provided - log.Println("DATABASE_DSN not set, using default local PostgreSQL DSN") - log.Println("IMPORTANT: Ensure PostgreSQL is running with the correct credentials.") - log.Println("Try creating a database 'finance' and setting up a user with the correct permissions.") - log.Println("Example commands:") - log.Println(" createdb finance") - log.Println(" createuser -P -s -e user_name") - - // Use more common/generic default credentials - dsn = "host=localhost user=postgres password=postgres dbname=finance port=5432 sslmode=disable TimeZone=UTC" - // Consider making the default conditional or removing it for stricter environments + return config, nil +} + +// getEnv gets an environment variable or returns a default value +func getEnv(key, defaultValue string) string { + value := os.Getenv(key) + if value == "" { + return defaultValue + } + return value +} + +// getEnvInt gets an environment variable as an integer or returns a default value +func getEnvInt(key string, defaultValue int) int { + value := os.Getenv(key) + if value == "" { + return defaultValue } - jwtSecret := os.Getenv("JWT_SECRET") - if jwtSecret == "" { - log.Println("WARNING: JWT_SECRET environment variable not set. Using an insecure default.") - // !!! IMPORTANT: Use a strong, randomly generated secret in production !!! - // For development only: - jwtSecret = "insecure-default-dev-secret-change-me" - // return nil, errors.New("JWT_SECRET environment variable is required") + intValue, err := parseInt(value) + if err != nil { + return defaultValue } - return &Config{ - DatabaseDSN: dsn, - JWTSecret: jwtSecret, - }, nil + return intValue +} + +// parseInt parses a string to an int +func parseInt(value string) (int, error) { + intValue := 0 + _, err := fmt.Sscanf(value, "%d", &intValue) + return intValue, err } diff --git a/backend/internal/logger/logger.go b/backend/internal/logger/logger.go new file mode 100644 index 0000000..7de276d --- /dev/null +++ b/backend/internal/logger/logger.go @@ -0,0 +1,144 @@ +package logger + +import ( + "fmt" + "io" + "log" + "os" + "time" +) + +// LogLevel represents the severity of a log message +type LogLevel int + +const ( + // DEBUG level for detailed information + DEBUG LogLevel = iota + // INFO level for general operational information + INFO + // WARN level for warnings + WARN + // ERROR level for errors + ERROR + // FATAL level for fatal errors that cause the application to exit + FATAL +) + +var ( + // defaultLogger is the default logger used by the package + defaultLogger *Logger + // level names for pretty printing + levelNames = []string{ + "DEBUG", + "INFO", + "WARN", + "ERROR", + "FATAL", + } +) + +// Logger is a custom logger that wraps the standard log package +type Logger struct { + debugLog *log.Logger + infoLog *log.Logger + warnLog *log.Logger + errorLog *log.Logger + fatalLog *log.Logger +} + +// Init initializes the default logger with the specified output and minimum log level +func Init(out io.Writer, level LogLevel) { + defaultLogger = NewLogger(out, level) +} + +// NewLogger creates a new logger with the specified output and minimum log level +func NewLogger(out io.Writer, level LogLevel) *Logger { + if out == nil { + out = os.Stdout + } + + flags := log.Ldate | log.Ltime + + l := &Logger{ + debugLog: log.New(out, "[DEBUG] ", flags), + infoLog: log.New(out, "[INFO] ", flags), + warnLog: log.New(out, "[WARN] ", flags), + errorLog: log.New(out, "[ERROR] ", flags), + fatalLog: log.New(out, "[FATAL] ", flags), + } + + return l +} + +// Debug logs a debug message +func (l *Logger) Debug(v ...interface{}) { + l.debugLog.Println(v...) +} + +// Info logs an info message +func (l *Logger) Info(v ...interface{}) { + l.infoLog.Println(v...) +} + +// Warn logs a warning message +func (l *Logger) Warn(v ...interface{}) { + l.warnLog.Println(v...) +} + +// Error logs an error message +func (l *Logger) Error(v ...interface{}) { + l.errorLog.Println(v...) +} + +// Fatal logs a fatal message and exits the program +func (l *Logger) Fatal(v ...interface{}) { + l.fatalLog.Println(v...) + os.Exit(1) +} + +// Debugf logs a formatted debug message +func (l *Logger) Debugf(format string, v ...interface{}) { + l.debugLog.Printf(format, v...) +} + +// Infof logs a formatted info message +func (l *Logger) Infof(format string, v ...interface{}) { + l.infoLog.Printf(format, v...) +} + +// Warnf logs a formatted warning message +func (l *Logger) Warnf(format string, v ...interface{}) { + l.warnLog.Printf(format, v...) +} + +// Errorf logs a formatted error message +func (l *Logger) Errorf(format string, v ...interface{}) { + l.errorLog.Printf(format, v...) +} + +// Fatalf logs a formatted fatal message and exits the program +func (l *Logger) Fatalf(format string, v ...interface{}) { + l.fatalLog.Printf(format, v...) + os.Exit(1) +} + +// LogRequest logs an HTTP request +func (l *Logger) LogRequest(method, path, ip, userAgent string, status int, latency time.Duration) { + l.Infof( + "Request: %s %s | Status: %d | IP: %s | User-Agent: %s | Latency: %v", + method, path, status, ip, userAgent, latency, + ) +} + +// GetTimestamp returns the current timestamp as a formatted string +func GetTimestamp() string { + return time.Now().Format("2006-01-02 15:04:05") +} + +// FormatRequestLog formats a request log entry with useful information +func FormatRequestLog(method, path, ip, userAgent string, statusCode int, latency time.Duration) string { + return fmt.Sprintf( + "Request: %s %s | Status: %d | IP: %s | Latency: %s | User-Agent: %s", + method, path, statusCode, ip, latency, userAgent, + ) +} diff --git a/backend/internal/middleware/error_handler.go b/backend/internal/middleware/error_handler.go new file mode 100644 index 0000000..4e7eedf --- /dev/null +++ b/backend/internal/middleware/error_handler.go @@ -0,0 +1,119 @@ +package middleware + +import ( + "finance/backend/internal/logger" + "net/http" + "runtime/debug" + "time" + + "github.com/gin-gonic/gin" +) + +// ErrorResponse represents a standardized error response +type ErrorResponse struct { + Status int `json:"status"` + Message string `json:"message"` + Error string `json:"error,omitempty"` +} + +// ErrorHandler middleware recovers from panics and logs errors +func ErrorHandler() gin.HandlerFunc { + return func(c *gin.Context) { + defer func() { + if err := recover(); err != nil { + // Get logger from the context or create a new one + log := getLoggerFromContext(c) + + // Log the stack trace + log.Errorf("PANIC RECOVERED: %v\n%s", err, debug.Stack()) + + // Return a 500 Internal Server Error response + c.JSON(http.StatusInternalServerError, ErrorResponse{ + Status: http.StatusInternalServerError, + Message: "An unexpected error occurred", + }) + + // Abort the request + c.Abort() + } + }() + + c.Next() + } +} + +// RequestLogger middleware logs information about each request +func RequestLogger(log *logger.Logger) gin.HandlerFunc { + return func(c *gin.Context) { + // Store logger in context for other middleware to use + c.Set("logger", log) + + // Start timer + startTime := time.Now() + + // Process request + c.Next() + + // Calculate latency + latency := time.Since(startTime) + + // Get request details + method := c.Request.Method + path := c.Request.URL.Path + statusCode := c.Writer.Status() + ip := c.ClientIP() + userAgent := c.Request.UserAgent() + + // Log request info based on status code + logMessage := logger.FormatRequestLog(method, path, ip, userAgent, statusCode, latency) + + if statusCode >= 500 { + log.Error(logMessage) + } else if statusCode >= 400 { + log.Warn(logMessage) + } else { + log.Info(logMessage) + } + } +} + +// NotFoundHandler handles 404 errors +func NotFoundHandler() gin.HandlerFunc { + return func(c *gin.Context) { + // Get logger from the context or create a new one + log := getLoggerFromContext(c) + + log.Warnf("404 Not Found: %s %s", c.Request.Method, c.Request.URL.Path) + c.JSON(http.StatusNotFound, ErrorResponse{ + Status: http.StatusNotFound, + Message: "The requested resource was not found", + }) + } +} + +// MethodNotAllowedHandler handles 405 errors +func MethodNotAllowedHandler() gin.HandlerFunc { + return func(c *gin.Context) { + // Get logger from the context or create a new one + log := getLoggerFromContext(c) + + log.Warnf("405 Method Not Allowed: %s %s", c.Request.Method, c.Request.URL.Path) + c.JSON(http.StatusMethodNotAllowed, ErrorResponse{ + Status: http.StatusMethodNotAllowed, + Message: "The requested method is not allowed", + }) + } +} + +// getLoggerFromContext retrieves the logger from context or creates a default one +func getLoggerFromContext(c *gin.Context) *logger.Logger { + loggerInterface, exists := c.Get("logger") + if exists { + if log, ok := loggerInterface.(*logger.Logger); ok { + return log + } + } + + // If no logger in context, create a new one + return logger.NewLogger(nil, logger.INFO) +} diff --git a/backend/middleware/middleware.go b/backend/middleware/middleware.go new file mode 100644 index 0000000..d319c47 --- /dev/null +++ b/backend/middleware/middleware.go @@ -0,0 +1,83 @@ +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() + } +} |