aboutsummaryrefslogtreecommitdiffstats
path: root/backend/middleware/middleware.go
blob: d319c47bb88fabaa34d13fcc54b1326bbb04a7a2 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
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()
	}
}