CORS middleware. And fix middleware types for logging and securityheaders.

This commit is contained in:
2025-04-28 02:47:22 -05:00
parent e8f22496e1
commit c2265330dd
4 changed files with 195 additions and 70 deletions

View File

@ -19,47 +19,49 @@ func (w *wrappedWriter) WriteHeader(statusCode int) {
}
// Logging is a middleware function that logs requests with structured logging
func Logging(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
func Logging() Middleware {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
// Prepare wrapped writer to capture status code
wrapped := &wrappedWriter{
ResponseWriter: w,
statusCode: http.StatusOK,
}
// Prepare wrapped writer to capture status code
wrapped := &wrappedWriter{
ResponseWriter: w,
statusCode: http.StatusOK,
}
// Get request ID from context
requestID := GetRequestID(r.Context())
// Get request ID from context
requestID := GetRequestID(r.Context())
// Get logger from the application and add request information
logger := logging.FromContext(r.Context())
reqLogger := logging.WithValues(logger,
slog.String("request_id", requestID),
slog.String("method", r.Method),
slog.String("path", r.URL.Path),
slog.String("remote_ip", r.RemoteAddr),
slog.String("user_agent", r.UserAgent()),
)
// Get logger from the application and add request information
logger := logging.FromContext(r.Context())
reqLogger := logging.WithValues(logger,
slog.String("request_id", requestID),
slog.String("method", r.Method),
slog.String("path", r.URL.Path),
slog.String("remote_ip", r.RemoteAddr),
slog.String("user_agent", r.UserAgent()),
)
// Store the request-specific logger in context
ctx := logging.WithContext(r.Context(), reqLogger)
r = r.WithContext(ctx)
// Store the request-specific logger in context
ctx := logging.WithContext(r.Context(), reqLogger)
r = r.WithContext(ctx)
// Log request start if in debug mode
reqLogger.Debug("request started")
// Log request start if in debug mode
reqLogger.Debug("request started")
// Process the request with updated context
next.ServeHTTP(wrapped, r)
// Process the request with updated context
next.ServeHTTP(wrapped, r)
// Calculate duration
duration := time.Since(start)
// Calculate duration
duration := time.Since(start)
// Log request completion with status and duration
reqLogger.Info("request completed",
slog.Int("status", wrapped.statusCode),
slog.Duration("duration", duration),
slog.String("duration_human", duration.String()),
)
})
// Log request completion with status and duration
reqLogger.Info("request completed",
slog.Int("status", wrapped.statusCode),
slog.Duration("duration", duration),
slog.String("duration_human", duration.String()),
)
})
}
}