MCPcopy Create free account
hub / github.com/pace/bricks / RequestIDHandler

Function RequestIDHandler

maintenance/log/handler.go:108–151  ·  view source on GitHub ↗
(fieldKey, headerName string)

Source from the content-addressed store, hash-verified

106}
107
108func 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}

Callers 1

HandlerFunction · 0.70

Calls 9

IDFromCtxFunction · 0.92
WithValueFunction · 0.92
ContextMethod · 0.80
WithContextMethod · 0.80
SetMethod · 0.80
HeaderMethod · 0.80
GetMethod · 0.65
StringMethod · 0.45
ServeHTTPMethod · 0.45

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…