middleware/request_id.go (view raw)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
package middleware import ( "context" "errors" "net/http" "brijesh.dev/toolkit/buid" ) func RequestIDMiddleware(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { requestID := buid.GenerateBUID() ctx := context.WithValue(r.Context(), "requestID", requestID) w.Header().Set("X-Request-ID", requestID) next.ServeHTTP(w, r.WithContext(ctx)) }) } func GetRequestID(r *http.Request) string { requestID := r.Context().Value("requestID").(string) if requestID == "" { panic(errors.New("calling GetRequestID without using RequestIDMiddleware")) } return requestID } |