Documentation
¶
Overview ¶
Package requestid assigns an ID to every request and exposes it through Context.ID, the "X-Request-Id" header and the `Get` function.
Its entry point is New(generator ...Generator), which returns a Handler. The variadic parameter is NOT a functional-options list: it is an optional domain-typed Generator (at most one is read), so that `requestid.New()` and `requestid.New(requestid.ServerOnlyGenerator)` both read naturally. The package has no settings beyond that, so there is no Options struct.
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func Hash ¶
Hash returns the hex-encoded sha256 hash of the request. It does not capture error, instead it returns an empty string.
func New ¶
New returns a new request id middleware. It optionally accepts an ID Generator. The Generator can stop the handlers chain with an error or return a valid ID (string). If it's missing then the `DefaultGenerator` will be used instead.
The variadic parameter is an optional Generator, not a functional-options list: only the first one is read.
Types ¶
type Generator ¶
Generator defines the function which should extract or generate a Request ID. See `DefaultGenerator` and `New` package-level functions.
var DefaultGenerator Generator = func(ctx *context.Context) string { id := ctx.ResponseWriter().Header().Get(xRequestIDHeaderKey) if id != "" { return id } if v := ctx.Header(xRequestIDHeaderKey); isValidRequestID(v) { id = v } if id == "" { id = uid.NewString() } ctx.SetHeader(xRequestIDHeaderKey, id) return id }
DefaultGenerator is the default `Generator` that is used when nil is passed on `New` package-level function. It extracts the ID from the "X-Request-ID" request header value or, if missing, it generates a new UUID(v4) and sets the header and context value.
Security note: DefaultGenerator trusts a client-supplied "X-Request-ID" header. If request IDs end up in logs or are otherwise trusted downstream and clients should not be able to choose or forge them (log injection / forgery), use ServerOnlyGenerator instead.
See `Get` package-level function too.
var ServerOnlyGenerator Generator = func(ctx *context.Context) string { if id := ctx.ResponseWriter().Header().Get(xRequestIDHeaderKey); id != "" { return id } id := uid.NewString() ctx.SetHeader(xRequestIDHeaderKey, id) return id }
ServerOnlyGenerator is a `Generator` that always generates a new server-side UUID(v4) and ignores any client-supplied "X-Request-ID" request header. Use it instead of DefaultGenerator when clients must not be able to choose or forge the request ID, for example to prevent log forgery via the header:
app.Use(requestid.New(requestid.ServerOnlyGenerator))
func HashGenerator ¶
HashGenerator uses the request's hash to generate a fixed-length Request ID. Note that one or many requests may contain the same ID, so it's not unique.