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)
| 212 | // size and ease of use: UUID is less space efficient and snowflake requires machine |
| 213 | // configuration. |
| 214 | func 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. |