github.com/shoshinnikita/budget-manager@v0.7.1-0.20220131195411-8c46ff1c6778/internal/web/middlewares/reqid.go (about) 1 package middlewares 2 3 import ( 4 "net/http" 5 6 "github.com/ShoshinNikita/budget-manager/internal/pkg/reqid" 7 ) 8 9 const requestIDHeader = "X-Request-ID" 10 11 // requestIDMeddleware generates a new request id and inserts it into the request context 12 func RequestIDMeddleware(h http.Handler) http.Handler { 13 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 14 reqID := reqid.New() 15 if headerValue := r.Header.Get(requestIDHeader); headerValue != "" { 16 reqID = reqid.RequestID(headerValue) 17 } 18 19 ctx := reqid.ToContext(r.Context(), reqID) 20 r = r.WithContext(ctx) 21 22 h.ServeHTTP(w, r) 23 }) 24 }