Add client RequestID middleware for cross-service propagation

Introduces internal/requestid package with shared context key to avoid
circular imports between server and middleware packages. Server's
RequestID middleware now uses the shared key. Client middleware picks up
the ID from context and sets X-Request-Id on outgoing requests.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-03-22 21:47:58 +03:00
parent 3395f70abd
commit 49be6f8a7e
4 changed files with 115 additions and 5 deletions

View File

@@ -5,9 +5,9 @@ import (
"crypto/rand"
"fmt"
"net/http"
)
type requestIDKey struct{}
"git.codelab.vc/pkg/httpx/internal/requestid"
)
// RequestID returns a middleware that assigns a unique request ID to each
// request. If the incoming request already has an X-Request-Id header, that
@@ -23,7 +23,7 @@ func RequestID() Middleware {
id = newUUID()
}
ctx := context.WithValue(r.Context(), requestIDKey{}, id)
ctx := requestid.NewContext(r.Context(), id)
w.Header().Set("X-Request-Id", id)
next.ServeHTTP(w, r.WithContext(ctx))
})
@@ -33,8 +33,7 @@ func RequestID() Middleware {
// RequestIDFromContext returns the request ID from the context, or an empty
// string if none is set.
func RequestIDFromContext(ctx context.Context) string {
id, _ := ctx.Value(requestIDKey{}).(string)
return id
return requestid.FromContext(ctx)
}
// newUUID generates a UUID v4 string using crypto/rand.