This commit is contained in:
2024-09-12 08:57:44 +10:00
commit eb10ca9ca3
35 changed files with 1354 additions and 0 deletions

View File

@@ -0,0 +1,34 @@
package middleware
import (
"log/slog"
"net/http"
"time"
)
// LoggingMiddleware represents a logging middleware.
type LoggingMiddleware struct {
logger *slog.Logger
handler http.Handler
}
// NewLoggingMiddleware creates a new logging middleware with the given logger and handler.
func NewLoggingMiddleware(logger *slog.Logger, handler http.Handler) *LoggingMiddleware {
return &LoggingMiddleware{
logger: logger,
handler: handler,
}
}
// ServeHTTP logs the request and calls the next handler.
func (l *LoggingMiddleware) ServeHTTP(w http.ResponseWriter, r *http.Request) {
start := time.Now()
l.handler.ServeHTTP(w, r)
l.logger.Debug(
"Request recieved",
slog.String("method", r.Method),
slog.String("path", r.URL.Path),
slog.String("remote", r.RemoteAddr),
slog.Duration("duration", time.Since(start)),
)
}