MCPcopy
hub / github.com/rs/zerolog / RequestIDHandler

Function RequestIDHandler

hlog/hlog.go:214–236  ·  view source on GitHub ↗

RequestIDHandler returns a handler setting a unique id to the request which can be gathered using IDFromRequest(req). This generated id is added as a field to the logger using the passed fieldKey as field name. The id is also added as a response header if the headerName is not empty. The generated

(fieldKey, headerName string)

Source from the content-addressed store, hash-verified

212// size and ease of use: UUID is less space efficient and snowflake requires machine
213// configuration.
214func RequestIDHandler(fieldKey, headerName string) func(next http.Handler) http.Handler {
215 return func(next http.Handler) http.Handler {
216 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
217 ctx := r.Context()
218 id, ok := IDFromRequest(r)
219 if !ok {
220 id = xid.New()
221 ctx = CtxWithID(ctx, id)
222 r = r.WithContext(ctx)
223 }
224 if fieldKey != "" {
225 log := zerolog.Ctx(ctx)
226 log.UpdateContext(func(c zerolog.Context) zerolog.Context {
227 return c.Str(fieldKey, id.String())
228 })
229 }
230 if headerName != "" {
231 w.Header().Set(headerName, id.String())
232 }
233 next.ServeHTTP(w, r)
234 })
235 }
236}
237
238// CustomHeaderHandler adds given header from request's header as a field to
239// the context's logger using fieldKey as field key.

Callers 1

TestRequestIDHandlerFunction · 0.85

Calls 8

CtxFunction · 0.92
IDFromRequestFunction · 0.85
CtxWithIDFunction · 0.85
WithContextMethod · 0.80
UpdateContextMethod · 0.80
SetMethod · 0.65
StrMethod · 0.45
StringMethod · 0.45

Tested by 1

TestRequestIDHandlerFunction · 0.68