// 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() }