Files
Sebastian UnterschützandClaude Opus 5.5 c485d1a96f feat(platform): tag requests, logs and api errors with a request id
A well-formed X-Request-ID from a proxy is kept, otherwise a UUIDv7 is
generated. The ID is echoed in the response header, added to every log
record written with the request context and returned in API error
bodies.

Closes #44

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-22 00:20:57 +01:00

54 lines
1.4 KiB
Go

// Package requestid assigns every HTTP request an ID that ties together the
// response, all log lines written for it and error reports from users.
package requestid
import (
"context"
"regexp"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
)
// Header carries the ID in both directions.
const Header = "X-Request-ID"
// Incoming IDs end up in logs and response headers, so anything beyond a
// conservative token alphabet is replaced rather than passed through.
var valid = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
type ctxKey struct{}
// NewContext returns ctx carrying id.
func NewContext(ctx context.Context, id string) context.Context {
return context.WithValue(ctx, ctxKey{}, id)
}
// FromContext returns the request ID in ctx, or "" outside a request.
func FromContext(ctx context.Context) string {
id, _ := ctx.Value(ctxKey{}).(string)
return id
}
// Middleware keeps a well-formed X-Request-ID set by a proxy in front of us
// and otherwise generates a time-ordered UUIDv7, so IDs sort by arrival.
// It must run before any middleware that logs.
func Middleware() gin.HandlerFunc {
return func(c *gin.Context) {
id := c.GetHeader(Header)
if !valid.MatchString(id) {
id = newID()
}
c.Request = c.Request.WithContext(NewContext(c.Request.Context(), id))
c.Header(Header, id)
c.Next()
}
}
func newID() string {
if id, err := uuid.NewV7(); err == nil {
return id.String()
}
return uuid.NewString()
}