-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.go
More file actions
179 lines (147 loc) · 4.16 KB
/
middleware.go
File metadata and controls
179 lines (147 loc) · 4.16 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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
package middleware
import (
"context"
"fmt"
"log/slog"
"net/http"
"strings"
"time"
)
type contextKey string
const (
TraceIDKey contextKey = "trace_id"
UserIDKey contextKey = "user_id"
RequestIDKey contextKey = "request_id"
)
type MiddlewareFunc func(http.Handler) http.Handler
type Middleware struct {
logger *slog.Logger
excludedPaths map[string]bool
excludedPrefix []string
}
func New(logger *slog.Logger) *Middleware {
if logger == nil {
logger = slog.Default()
}
mw := &Middleware{
logger: logger,
excludedPaths: make(map[string]bool),
excludedPrefix: make([]string, 0),
}
return mw
}
// Chain combines middlewares and returns a handler.
// Build chain from right to left
func (m *Middleware) Chain(middlewares ...MiddlewareFunc) MiddlewareFunc {
return func(handler http.Handler) http.Handler {
// Build chain from right to left
for i := len(middlewares) - 1; i >= 0; i-- {
handler = middlewares[i](handler)
}
return handler
}
}
// ExcludePaths excludes exact path matches
// Example: mw.ExcludePaths("/health")
func (m *Middleware) ExcludePaths(paths ...string) {
for _, path := range paths {
m.excludedPaths[path] = true
}
}
// ExcludePrefixes excludes paths starting with given prefixes
// Example: mw.ExcludePrefixes("/health/")
func (m *Middleware) ExcludePrefixes(prefixes ...string) {
m.excludedPrefix = append(m.excludedPrefix, prefixes...)
}
// shouldSkip checks if request should skip middleware
func (m *Middleware) ShouldSkip(r *http.Request) bool {
path := r.URL.Path
// Check exact path matches (O(1) lookup)
if m.excludedPaths[path] {
return true
}
// Check prefix matches (O(n) but typically very small n)
for _, prefix := range m.excludedPrefix {
if strings.HasPrefix(path, prefix) {
return true
}
}
return false
}
// LogRequest logs HTTP requests with response details
func (m *Middleware) LogRequest(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if m.ShouldSkip(r) {
next.ServeHTTP(w, r)
return
}
start := time.Now()
traceID := getTraceID(r)
// Add trace ID to context
ctx := context.WithValue(r.Context(), TraceIDKey, traceID)
r = r.WithContext(ctx)
// Wrap response writer to capture status and size
wrapped := &responseWriter{ResponseWriter: w, statusCode: http.StatusOK}
next.ServeHTTP(wrapped, r)
m.logger.Info("request",
slog.String("trace_id", traceID),
slog.String("method", r.Method),
slog.String("path", r.URL.Path),
slog.Int("status", wrapped.statusCode),
slog.Int("size", wrapped.size),
slog.Duration("duration", time.Since(start)),
)
})
}
// RecoverPanic recovers from panics
func (m *Middleware) RecoverPanic(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if err := recover(); err != nil {
traceID := GetTraceIDFromContext(r.Context())
m.logger.Error("panic recovered",
slog.String("trace_id", traceID),
slog.String("method", r.Method),
slog.String("path", r.URL.Path),
slog.Any("error", err),
)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusInternalServerError)
fmt.Fprintf(w, `{"error":"internal server error","trace_id":"%s"}`, traceID)
}
}()
next.ServeHTTP(w, r)
})
}
// responseWriter captures response metadata
type responseWriter struct {
http.ResponseWriter
statusCode int
size int
}
func (rw *responseWriter) WriteHeader(code int) {
rw.statusCode = code
rw.ResponseWriter.WriteHeader(code)
}
func (rw *responseWriter) Write(data []byte) (int, error) {
size, err := rw.ResponseWriter.Write(data)
rw.size += size
return size, err
}
// GetTraceIDFromContext returns the trace id from the context
func GetTraceIDFromContext(ctx context.Context) string {
if id, ok := ctx.Value(TraceIDKey).(string); ok {
return id
}
return "unknown"
}
// Helper functions
func getTraceID(r *http.Request) string {
headers := []string{"X-Trace-Id", "X-Request-Id", "X-Correlation-Id"}
for _, header := range headers {
if id := r.Header.Get(header); id != "" {
return id
}
}
return fmt.Sprintf("%d", time.Now().UnixNano())
}