error-pages/internal/http/middleware/logreq/middleware.go

50 lines
1.3 KiB
Go
Raw Normal View History

2024-06-22 20:05:11 +00:00
package logreq
import (
"net/http"
"time"
2024-06-24 15:28:03 +00:00
"gh.tarampamp.am/error-pages/internal/logger"
2024-06-22 20:05:11 +00:00
)
// New creates a middleware for [http.ServeMux] that logs every incoming request.
//
// The skipper function should return true if the request should be skipped. It's ok to pass nil.
2024-06-24 15:28:03 +00:00
func New(log *logger.Logger, skipper func(*http.Request) bool) func(http.Handler) http.Handler {
2024-06-22 20:05:11 +00:00
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if skipper != nil && skipper(r) {
next.ServeHTTP(w, r)
return
}
var now = time.Now()
defer func() {
2024-06-24 15:28:03 +00:00
var fields = []logger.Attr{
logger.String("useragent", r.UserAgent()),
logger.String("method", r.Method),
logger.String("url", r.URL.String()),
logger.String("referer", r.Referer()),
logger.String("content type", w.Header().Get("Content-Type")),
logger.String("remote addr", r.RemoteAddr),
logger.String("method", r.Method),
logger.Duration("duration", time.Since(now).Round(time.Microsecond)),
2024-06-22 20:05:11 +00:00
}
2024-06-24 15:28:03 +00:00
if log.Level() <= logger.DebugLevel {
2024-06-22 20:05:11 +00:00
fields = append(fields,
2024-06-24 15:28:03 +00:00
logger.Any("request headers", r.Header.Clone()),
logger.Any("response headers", w.Header().Clone()),
2024-06-22 20:05:11 +00:00
)
}
log.Info("HTTP request processed", fields...)
}()
next.ServeHTTP(w, r)
})
}
}