HLogRequestIDHandler provides a middleware that injects request_id into the logging and execution context. It prefers the X-Request-Id header, if that doesn't exist it creates a new request id similar to zerolog.
()
| 34 | // HLogRequestIDHandler provides a middleware that injects request_id into the logging and execution context. |
| 35 | // It prefers the X-Request-Id header, if that doesn't exist it creates a new request id similar to zerolog. |
| 36 | func HLogRequestIDHandler() func(http.Handler) http.Handler { |
| 37 | return func(h http.Handler) http.Handler { |
| 38 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 39 | ctx := r.Context() |
| 40 | |
| 41 | // read requestID from header (or create new one if none exists) |
| 42 | var reqID string |
| 43 | if reqIDs, ok := r.Header[requestIDHeader]; ok && len(reqIDs) > 0 && len(reqIDs[0]) > 0 { |
| 44 | reqID = reqIDs[0] |
| 45 | } else { |
| 46 | // similar to zerolog requestID generation |
| 47 | reqID = xid.New().String() |
| 48 | } |
| 49 | |
| 50 | // add requestID to context for internal usage client! |
| 51 | ctx = request.WithRequestID(ctx, reqID) |
| 52 | ctx = git.WithRequestID(ctx, reqID) |
| 53 | |
| 54 | // update logging context with request ID |
| 55 | logging.UpdateContext(ctx, logging.WithRequestID(reqID)) |
| 56 | |
| 57 | // write request ID to response headers |
| 58 | w.Header().Set(requestIDHeader, reqID) |
| 59 | |
| 60 | // continue serving request |
| 61 | h.ServeHTTP(w, r.WithContext(ctx)) |
| 62 | }) |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | // HLogAccessLogHandler provides an hlog based middleware that logs access logs. |
| 67 | func HLogAccessLogHandler() func(http.Handler) http.Handler { |
no test coverage detected
searching dependent graphs…