(fieldKey, headerName string)
| 106 | } |
| 107 | |
| 108 | func RequestIDHandler(fieldKey, headerName string) func(next http.Handler) http.Handler { |
| 109 | return func(next http.Handler) http.Handler { |
| 110 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 111 | ctx := r.Context() |
| 112 | var id xid.ID |
| 113 | |
| 114 | // try extract of xid from header |
| 115 | reqID := r.Header.Get(headerName) |
| 116 | if reqID != "" { |
| 117 | id, _ = xid.FromString(reqID) |
| 118 | } |
| 119 | |
| 120 | // try extract of xid context |
| 121 | if id.Compare(xid.NilID()) == 0 { |
| 122 | if nid, ok := hlog.IDFromCtx(ctx); ok { |
| 123 | id = nid |
| 124 | } |
| 125 | } |
| 126 | |
| 127 | // give up, generate a new xid |
| 128 | if id.Compare(xid.NilID()) == 0 { |
| 129 | id = xid.New() |
| 130 | } |
| 131 | |
| 132 | ctx = hlog.WithValue(ctx, id) |
| 133 | r = r.WithContext(ctx) |
| 134 | |
| 135 | transaction := sentry.TransactionFromContext(ctx) |
| 136 | if transaction != nil { |
| 137 | transaction.SetData("http.request.id", id.String()) |
| 138 | } |
| 139 | |
| 140 | // log requests with request id |
| 141 | log := zerolog.Ctx(ctx) |
| 142 | log.UpdateContext(func(c zerolog.Context) zerolog.Context { |
| 143 | return c.Str(fieldKey, id.String()) |
| 144 | }) |
| 145 | |
| 146 | // return the request id as a header to the client |
| 147 | w.Header().Set(headerName, id.String()) |
| 148 | next.ServeHTTP(w, r) |
| 149 | }) |
| 150 | } |
| 151 | } |
no test coverage detected
searching dependent graphs…