-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathmiddleware.go
More file actions
257 lines (220 loc) · 6.63 KB
/
Copy pathmiddleware.go
File metadata and controls
257 lines (220 loc) · 6.63 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
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
// Package internal provides HTTP middleware for github-copilot-svcs.
package internal
import (
"bufio"
"bytes"
"encoding/json"
"io"
"net"
"net/http"
"strings"
"time"
)
// HTTP status code constants
const (
statusServerError = 500
statusClientError = 400
)
// LoggingResponseWriter wraps http.ResponseWriter to capture response data and status code.
type LoggingResponseWriter struct {
http.ResponseWriter
statusCode int
body *bytes.Buffer
}
// NewLoggingResponseWriter ...
func NewLoggingResponseWriter(w http.ResponseWriter) *LoggingResponseWriter {
return &LoggingResponseWriter{
ResponseWriter: w,
statusCode: http.StatusOK,
body: bytes.NewBuffer(nil),
}
}
// WriteHeader ...
func (lrw *LoggingResponseWriter) WriteHeader(code int) {
lrw.statusCode = code
lrw.ResponseWriter.WriteHeader(code)
}
func (lrw *LoggingResponseWriter) Write(body []byte) (int, error) {
// Write to both the original response and our buffer
lrw.body.Write(body)
return lrw.ResponseWriter.Write(body)
}
// Hijack ...
func (lrw *LoggingResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
if hijacker, ok := lrw.ResponseWriter.(http.Hijacker); ok {
return hijacker.Hijack()
}
return nil, nil, http.ErrNotSupported
}
// StatusCode ...
func (lrw *LoggingResponseWriter) StatusCode() int {
return lrw.statusCode
}
// Body ...
func (lrw *LoggingResponseWriter) Body() []byte {
return lrw.body.Bytes()
}
// LoggingMiddleware logs HTTP requests and responses, including status code and duration.
func LoggingMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
// Create logging response writer
lrw := NewLoggingResponseWriter(w)
// Read and store request body for logging (if reasonable size)
var requestBody []byte
if r.Body != nil && r.ContentLength > 0 && r.ContentLength < 1024*1024 { // Max 1MB for logging
requestBody, _ = io.ReadAll(r.Body)
r.Body = io.NopCloser(bytes.NewBuffer(requestBody))
}
// Attempt to extract model field (if JSON body present and small enough)
modelName := ""
if len(requestBody) > 0 {
var tmp struct {
Model string `json:"model"`
}
if err := json.Unmarshal(requestBody, &tmp); err == nil && tmp.Model != "" {
modelName = tmp.Model
}
}
// Log request
if modelName != "" {
Info("HTTP Request",
"method", r.Method,
"url", r.URL.String(),
"model", modelName,
"remote_addr", getClientIP(r),
"user_agent", r.UserAgent(),
"content_length", r.ContentLength,
"has_body", len(requestBody) > 0,
)
} else {
Info("HTTP Request",
"method", r.Method,
"url", r.URL.String(),
"remote_addr", getClientIP(r),
"user_agent", r.UserAgent(),
"content_length", r.ContentLength,
"has_body", len(requestBody) > 0,
)
}
// Process request
next.ServeHTTP(lrw, r)
// Calculate duration
duration := time.Since(start)
// Determine log level based on status code
statusCode := lrw.StatusCode()
responseSize := len(lrw.Body())
logArgs := []interface{}{
"method", r.Method,
"url", r.URL.String(),
"status_code", statusCode,
"duration_ms", duration.Milliseconds(),
"response_size", responseSize,
"remote_addr", getClientIP(r),
}
// Log response with appropriate level
switch {
case statusCode >= statusServerError:
Error("HTTP Response", logArgs...)
case statusCode >= statusClientError:
Warn("HTTP Response", logArgs...)
default:
Info("HTTP Response", logArgs...)
}
// Log response body for debugging if it's small and there was an error
if statusCode >= 400 && responseSize > 0 && responseSize < 1024 {
Debug("HTTP Response Body", "body", string(lrw.Body()))
}
})
}
// RecoveryMiddleware ...
func RecoveryMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
defer func() {
if err := recover(); err != nil {
Error("HTTP Handler Panic",
"error", err,
"method", r.Method,
"url", r.URL.String(),
"remote_addr", getClientIP(r),
)
WriteInternalError(w)
}
}()
next.ServeHTTP(w, r)
})
}
// CORSMiddleware ...
func CORSMiddleware(config *Config) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
origin := r.Header.Get("Origin")
// Set CORS headers based on configuration
if len(config.CORS.AllowedOrigins) > 0 {
if containsOrigin(config.CORS.AllowedOrigins, origin) || containsOrigin(config.CORS.AllowedOrigins, "*") {
w.Header().Set("Access-Control-Allow-Origin", origin)
}
}
if len(config.CORS.AllowedHeaders) > 0 {
w.Header().Set("Access-Control-Allow-Headers", strings.Join(config.CORS.AllowedHeaders, ", "))
}
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
w.Header().Set("Access-Control-Allow-Credentials", "true")
// Handle preflight requests
if r.Method == "OPTIONS" {
w.WriteHeader(http.StatusOK)
return
}
next.ServeHTTP(w, r)
})
}
}
// SecurityHeadersMiddleware ...
func SecurityHeadersMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Security headers
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("X-Frame-Options", "DENY")
w.Header().Set("X-XSS-Protection", "1; mode=block")
w.Header().Set("Referrer-Policy", "strict-origin-when-cross-origin")
// Only set HSTS for HTTPS requests
if r.TLS != nil {
w.Header().Set("Strict-Transport-Security", "max-age=31536000; includeSubDomains")
}
next.ServeHTTP(w, r)
})
}
// TimeoutMiddleware sets a timeout for HTTP requests using http.TimeoutHandler.
func TimeoutMiddleware(timeout time.Duration) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.TimeoutHandler(next, timeout, "Request timeout")
}
}
// Helper functions
func getClientIP(r *http.Request) string {
// Check X-Forwarded-For header (proxy)
if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
// Take the first IP in the chain
if idx := strings.Index(xff, ","); idx != -1 {
return strings.TrimSpace(xff[:idx])
}
return strings.TrimSpace(xff)
}
// Check X-Real-IP header (nginx)
if xri := r.Header.Get("X-Real-IP"); xri != "" {
return strings.TrimSpace(xri)
}
// Fall back to RemoteAddr
if ip, _, err := net.SplitHostPort(r.RemoteAddr); err == nil {
return ip
}
return r.RemoteAddr
}
func containsOrigin(origins []string, origin string) bool {
for _, o := range origins {
if o == origin || o == "*" {
return true
}
}
return false
}