mirror of
https://github.com/netbirdio/netbird.git
synced 2026-04-18 00:06:38 +00:00
56 lines
1.2 KiB
Go
56 lines
1.2 KiB
Go
package middleware
|
|
|
|
import (
|
|
"net/http"
|
|
"time"
|
|
|
|
log "github.com/sirupsen/logrus"
|
|
)
|
|
|
|
// responseWriter wraps http.ResponseWriter to capture status code
|
|
type responseWriter struct {
|
|
http.ResponseWriter
|
|
statusCode int
|
|
written int64
|
|
}
|
|
|
|
func (rw *responseWriter) WriteHeader(code int) {
|
|
rw.statusCode = code
|
|
rw.ResponseWriter.WriteHeader(code)
|
|
}
|
|
|
|
func (rw *responseWriter) Write(b []byte) (int, error) {
|
|
n, err := rw.ResponseWriter.Write(b)
|
|
rw.written += int64(n)
|
|
return n, err
|
|
}
|
|
|
|
// Logging middleware logs HTTP requests with details
|
|
func Logging(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
start := time.Now()
|
|
|
|
// Wrap the response writer
|
|
wrapped := &responseWriter{
|
|
ResponseWriter: w,
|
|
statusCode: http.StatusOK,
|
|
}
|
|
|
|
// Call the next handler
|
|
next.ServeHTTP(wrapped, r)
|
|
|
|
// Log request details
|
|
duration := time.Since(start)
|
|
|
|
log.WithFields(log.Fields{
|
|
"method": r.Method,
|
|
"path": r.URL.Path,
|
|
"status": wrapped.statusCode,
|
|
"duration_ms": duration.Milliseconds(),
|
|
"bytes": wrapped.written,
|
|
"remote_addr": r.RemoteAddr,
|
|
"user_agent": r.UserAgent(),
|
|
}).Info("HTTP request")
|
|
})
|
|
}
|