AttachRequestID adds a request ID to each HTTP request.
(next http.Handler)
| 35 | |
| 36 | // AttachRequestID adds a request ID to each HTTP request. |
| 37 | func AttachRequestID(next http.Handler) http.Handler { |
| 38 | return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { |
| 39 | rid := uuid.New() |
| 40 | ridString := rid.String() |
| 41 | |
| 42 | ctx := context.WithValue(r.Context(), requestIDContextKey{}, rid) |
| 43 | ctx = slog.With(ctx, slog.F("request_id", rid)) |
| 44 | |
| 45 | trace.SpanFromContext(ctx). |
| 46 | SetAttributes(attribute.String("request_id", rid.String())) |
| 47 | |
| 48 | rw.Header().Set("X-Coder-Request-Id", ridString) |
| 49 | next.ServeHTTP(rw, r.WithContext(ctx)) |
| 50 | }) |
| 51 | } |