tracing.go 547 B

123456789101112131415161718192021
  1. package middleware
  2. import (
  3. "context"
  4. "net/http"
  5. )
  6. // Tracing is a middleware to trace HTTP request
  7. func Tracing(nextRequestID func() string) Middleware {
  8. return func(next http.Handler) http.Handler {
  9. return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
  10. requestID := r.Header.Get("X-Request-Id")
  11. if requestID == "" {
  12. requestID = nextRequestID()
  13. }
  14. ctx := context.WithValue(r.Context(), requestIDKey, requestID)
  15. w.Header().Set("X-Request-Id", requestID)
  16. next.ServeHTTP(w, r.WithContext(ctx))
  17. })
  18. }
  19. }