func SlogMiddleware()

in internal/middleware_logger/middleware_logger.go [12:43]


func SlogMiddleware(logger *slog.Logger) func(next http.Handler) http.Handler {
	return func(next http.Handler) http.Handler {
		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			start := time.Now()

			// Wrap the ResponseWriter to capture the status and any potential errors
			ww := &enhancedWriter{ResponseWriter: w, status: http.StatusOK}

			// Process the request
			next.ServeHTTP(ww, r)

			// Log the request details
			duration := time.Since(start)
			logFields := []any{
				"method", r.Method,
				"path", r.URL.Path,
				"host", r.Host,
				"status", ww.status,
				"duration_ms", duration.Milliseconds(),
			}

			// Include error message if available
			if ww.errMessage != "" {
				logFields = append(logFields, "error", ww.errMessage)
				logger.Error("HTTP request", logFields...)
				return
			}

			logger.Info("HTTP request", logFields...)
		})
	}
}