package httpx import ( "crypto/rand" "encoding/hex" "fmt" "log/slog" "net/http" "runtime/debug" "time" "github.com/gin-gonic/gin" ) // requestID assigns a fresh identifier to every request. // // An incoming X-Request-Id is deliberately not reused. This service is // client-facing: there is no trusted upstream that could have minted the // value, so honouring it would let any caller pick an arbitrary string that // ends up in logs (log injection, unbounded length) or collides with another // request and corrupts log correlation. Reusing the header is the right // choice only when the caller is a trusted proxy or a sibling service that // propagates one id across a chain of calls. func requestID(log *slog.Logger) gin.HandlerFunc { return func(c *gin.Context) { var raw [16]byte if _, err := rand.Read(raw[:]); err != nil { panic("httpx: random source unavailable: " + err.Error()) } id := hex.EncodeToString(raw[:]) c.Set(keyRequestID, id) c.Set(keyLogger, log) c.Writer.Header().Set("X-Request-Id", id) c.Next() } } // accessLog writes one line per request at a level that follows the // outcome (2xx debug, 4xx info, 5xx error), so the ordinary log level decides // how much traffic is recorded. Headers, query strings and bodies are never // recorded. time.Since uses the monotonic clock, so wall clock adjustments // cannot distort the duration. func accessLog() gin.HandlerFunc { return func(c *gin.Context) { start := time.Now() c.Next() status := c.Writer.Status() level := slog.LevelDebug switch { case status >= http.StatusInternalServerError: level = slog.LevelError case status >= http.StatusBadRequest: level = slog.LevelInfo } log := logger(c) ctx := c.Request.Context() if !log.Enabled(ctx, level) { return } attrs := []any{ "request_id", RequestID(c), "method", c.Request.Method, "path", c.Request.URL.Path, "status", status, "duration_ms", float64(time.Since(start).Microseconds()) / 1000, "bytes", c.Writer.Size(), } if id, ok := UserID(c); ok { attrs = append(attrs, "user_id", id.String()) } log.Log(ctx, level, "request", attrs...) } } // recovery turns a panic into a contract 500; the stack goes to the log only. func recovery() gin.HandlerFunc { return func(c *gin.Context) { defer func() { if r := recover(); r != nil { logger(c).Error("panic recovered", "request_id", RequestID(c), "panic", fmt.Sprint(r), "stack", string(debug.Stack()), ) if !c.Writer.Written() { Fail(c, http.StatusInternalServerError, "internal_error", "internal error") } c.Abort() } }() c.Next() } } // bodyLimit caps request bodies; exceeding it surfaces from the JSON // decoder as *http.MaxBytesError. func bodyLimit(maxBytes int64) gin.HandlerFunc { return func(c *gin.Context) { if c.Request.Body != nil { c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, maxBytes) } c.Next() } }