-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.go
More file actions
103 lines (86 loc) · 2.85 KB
/
middleware.go
File metadata and controls
103 lines (86 loc) · 2.85 KB
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package service
import (
"context"
"log/slog"
"net/http"
)
// ContextKey is a custom type for context keys to avoid collisions
type ContextKey string
const (
// LoggerKey is the context key for the logger
LoggerKey ContextKey = "logger"
// MetricsKey is the context key for metrics
MetricsKey ContextKey = "metrics"
// HealthCheckerKey is the context key for the health checker
HealthCheckerKey ContextKey = "health_checker"
)
// Middleware represents a middleware function
type Middleware func(http.Handler) http.Handler
// LoggerMiddleware injects the logger into the request context
func LoggerMiddleware(logger *slog.Logger) Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Create a new context with the logger
ctx := context.WithValue(r.Context(), LoggerKey, logger)
// Create a new request with the updated context
r = r.WithContext(ctx)
// Call the next handler
next.ServeHTTP(w, r)
})
}
}
// GetLogger retrieves the logger from the request context
func GetLogger(r *http.Request) *slog.Logger {
logger, ok := r.Context().Value(LoggerKey).(*slog.Logger)
if !ok {
// Return a default logger if none is found
return slog.Default()
}
return logger
}
// RecoveryMiddleware recovers from panics and logs them
func RecoveryMiddleware(logger *slog.Logger) Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if err := recover(); err != nil {
logger.Error("panic recovered", "error", err, "path", r.URL.Path, "method", r.Method)
http.Error(w, "Internal Server Error", http.StatusInternalServerError)
}
}()
next.ServeHTTP(w, r)
})
}
}
// RequestLoggingMiddleware logs incoming requests
func RequestLoggingMiddleware(logger *slog.Logger) Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
logger.Info("incoming request",
"method", r.Method,
"path", r.URL.Path,
"remote_addr", r.RemoteAddr,
"user_agent", r.UserAgent())
next.ServeHTTP(w, r)
})
}
}
// HealthCheckerMiddleware injects the health checker into the request context
func HealthCheckerMiddleware(healthChecker *HealthChecker) Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Add health checker to context
ctx := context.WithValue(r.Context(), HealthCheckerKey, healthChecker)
r = r.WithContext(ctx)
// Call the next handler
next.ServeHTTP(w, r)
})
}
}
// applyMiddleware applies multiple middleware functions to a handler
func applyMiddleware(h http.Handler, middlewares ...Middleware) http.Handler {
for i := len(middlewares) - 1; i >= 0; i-- {
h = middlewares[i](h)
}
return h
}