linstrom/web/public/middleware/traceRequestInfo.go
mstar 68d7a5e8c3
Some checks are pending
/ docker (push) Waiting to run
Start work on own tls termination and http3 support
2025-05-26 17:10:46 +02:00

41 lines
957 B
Go

package webmiddleware
import (
"bytes"
"io"
"net/http"
"time"
webutils "git.mstar.dev/mstar/goutils/http"
"github.com/rs/zerolog/hlog"
)
func TraceRequestInfoMiddleware(h http.Handler) http.Handler {
return webutils.ChainMiddlewares(
h,
hlog.AccessHandler(func(r *http.Request, status, size int, duration time.Duration) {
if !hlog.FromRequest(r).Trace().Enabled() {
return
}
body, _ := io.ReadAll(r.Body)
r.Body = io.NopCloser(bytes.NewReader(body))
IPAddress := r.Header.Get("X-Real-Ip")
if IPAddress == "" {
IPAddress = r.Header.Get("X-Forwarded-For")
}
if IPAddress == "" {
IPAddress = r.RemoteAddr
}
hlog.FromRequest(r).Trace().Any("headers", r.Header).
Str("proto", r.Proto).
Bytes("body", body).
Str("method", r.Method).
Stringer("url", r.URL).
Int("status", status).
Int("size", size).
Str("real-ip", IPAddress).
Dur("duration", duration).
Send()
}),
)
}