From 3ac7cd89a4009b3f3dce050934275dd1e2922273 Mon Sep 17 00:00:00 2001 From: Go Yakami Date: Mon, 7 Sep 2026 22:42:15 +0900 Subject: [PATCH] fix: use NewRequestWithContext to preserve request context in proxy Signed-off-by: Go Yakami --- handler/handler.go | 4 ++-- handler/handler_test.go | 18 ++++++++++++++++++ 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/handler/handler.go b/handler/handler.go index 23f1ca9..353da0a 100644 --- a/handler/handler.go +++ b/handler/handler.go @@ -67,9 +67,9 @@ func New(cfg config.Proxy, bp httputil.BufferPool, prov service.Authorizationd, u := *r.URL u.Scheme = scheme u.Host = host - req, err := http.NewRequest(r.Method, u.String(), r.Body) + req, err := http.NewRequestWithContext(r.Context(), r.Method, u.String(), r.Body) if err != nil { - glg.Error(errors.Wrap(err, "NewRequest returned error")) + glg.Error(errors.Wrap(err, "NewRequestWithContext returned error")) r.URL.Scheme = scheme return } diff --git a/handler/handler_test.go b/handler/handler_test.go index 1bf1501..625d88c 100644 --- a/handler/handler_test.go +++ b/handler/handler_test.go @@ -582,6 +582,24 @@ func TestNew(t *testing.T) { } } +func TestNew_DirectorPreservesRequestContext(t *testing.T) { + proxy := New(config.Proxy{ + Host: "127.0.0.1", + Port: 8080, + }, nil, nil, nil).(*httputil.ReverseProxy) + + ctx, cancel := context.WithCancel(context.Background()) + req := httptest.NewRequest(http.MethodGet, "http://example.com", nil).WithContext(ctx) + proxy.Director(req) + cancel() + + select { + case <-req.Context().Done(): + case <-time.After(time.Second): + t.Fatal("request context was not canceled") + } +} + func Test_updateDialContext(t *testing.T) { type args struct { cfg *http.Transport