Documentation
¶
Index ¶
- Variables
- func FromContext(ctx context.Context) string
- func LogHandler(handler slog.Handler) slog.Handler
- func Middleware(next http.Handler) http.Handler
- func New() string
- func NewContext(ctx context.Context) context.Context
- func SetHeader(ctx context.Context, req *http.Request)
- func Transport(next http.RoundTripper) http.RoundTripper
- type RequestID
- type RoundTripFunc
Constants ¶
This section is empty.
Variables ¶
var Header = http.CanonicalHeaderKey("Request-Id")
Header is the HTTP header used to propagate the request ID across services.
var LogKey string = "requestId"
LogKey is the slog attribute key used to log the request ID.
var MaxClockDrift = 5 * time.Minute
MaxClockDrift bounds how far the timestamp embedded in an inbound Request-Id may deviate from the server clock. IDs outside this window are discarded and replaced with a freshly minted one.
Defaults to 5 minutes. Set to 0 to disable the drift check.
Functions ¶
func FromContext ¶
FromContext returns the request ID stored in ctx, or "" if none is set.
func LogHandler ¶
LogHandler wraps an slog.Handler so that any log record produced via the *Context variants automatically carries the request ID from ctx.
slog.Log() slog.DebugContext() slog.InfoContext() slog.WarnContext() slog.ErrorContext()
Example:
ctx := requestid.NewContext(context.Background()) handler := requestid.LogHandler(slog.NewJSONHandler(os.Stdout, nil)) logger := slog.New(handler) logger.InfoContext(ctx, "message")
This would log
{"time":"2025-04-01T13:17:43.097789397Z","level":"INFO","msg":"message","requestId":"req_01kmfjypewe1wrfeb01wjfxand"}
func Middleware ¶
Middleware reads the request ID from the inbound Request-Id header, validates it as a typeid (req_…) whose embedded UUIDv7 timestamp is within MaxClockDrift of the server clock, and otherwise mints a fresh one. The (possibly new) ID is echoed on the response and stored in ctx.
func New ¶
func New() string
New mints a fresh request ID in the canonical "req_…" form.
Panics only if the OS clock is unreadable, which is treated as unrecoverable.
func NewContext ¶
NewContext returns ctx with a request ID attached. If ctx already carries one, it is returned unchanged.
func SetHeader ¶
SetHeader writes the request ID from ctx onto req. If ctx has no request ID, a fresh one is minted for the header (but not stored back into ctx).
func Transport ¶
func Transport(next http.RoundTripper) http.RoundTripper
Transport is an http.RoundTripper middleware that sets the Request-Id header on every outbound request, using the ID from ctx or a freshly minted one.
Types ¶
type RoundTripFunc ¶
RoundTripFunc, similar to http.HandlerFunc, is an adapter to allow the use of ordinary functions as http.RoundTrippers.