RequestID returns a middleware that adds a request ID to the context.
()
| 13 | |
| 14 | // RequestID returns a middleware that adds a request ID to the context. |
| 15 | func RequestID() func(http.Handler) http.Handler { |
| 16 | return func(next http.Handler) http.Handler { |
| 17 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 18 | id := r.Header.Get("X-Request-ID") |
| 19 | if id == "" { |
| 20 | b := make([]byte, 16) |
| 21 | _, _ = rand.Read(b) |
| 22 | id = hex.EncodeToString(b) |
| 23 | } |
| 24 | w.Header().Set("X-Request-ID", id) |
| 25 | ctx := context.WithValue(r.Context(), RequestIDKey, id) |
| 26 | next.ServeHTTP(w, r.WithContext(ctx)) |
| 27 | }) |
| 28 | } |
| 29 | } |