diff --git a/caddyconfig/httploader.go b/caddyconfig/httploader.go index a0a46460a..5b3896a2e 100644 --- a/caddyconfig/httploader.go +++ b/caddyconfig/httploader.go @@ -95,7 +95,7 @@ func (hl HTTPLoader) LoadConfig(ctx caddy.Context) ([]byte, error) { } url := repl.ReplaceAll(hl.URL, "") - req, err := http.NewRequest(method, url, nil) + req, err := http.NewRequestWithContext(ctx, method, url, nil) if err != nil { return nil, err } diff --git a/caddyconfig/httploader_test.go b/caddyconfig/httploader_test.go new file mode 100644 index 000000000..0f8a6dda0 --- /dev/null +++ b/caddyconfig/httploader_test.go @@ -0,0 +1,76 @@ +// Copyright 2015 Matthew Holt and The Caddy Authors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package caddyconfig + +import ( + "context" + "errors" + "net/http" + "net/http/httptest" + "testing" + "time" + + "github.com/caddyserver/caddy/v2" +) + +func TestHTTPLoaderLoadConfigRespectsContextCancellation(t *testing.T) { + requestStarted := make(chan struct{}) + requestCanceled := make(chan struct{}) + stopServer := make(chan struct{}) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + close(requestStarted) + select { + case <-r.Context().Done(): + close(requestCanceled) + case <-stopServer: + } + })) + t.Cleanup(func() { + close(stopServer) + srv.Close() + }) + + ctx, cancel := caddy.NewContext(caddy.Context{Context: context.Background()}) + loader := HTTPLoader{URL: srv.URL} + + errCh := make(chan error, 1) + go func() { + _, err := loader.LoadConfig(ctx) + errCh <- err + }() + + select { + case <-requestStarted: + case <-time.After(time.Second): + t.Fatal("request did not reach test server") + } + + cancel() + + select { + case err := <-errCh: + if !errors.Is(err, context.Canceled) { + t.Fatalf("expected context cancellation error, got %v", err) + } + case <-time.After(time.Second): + t.Fatal("LoadConfig did not return after context cancellation") + } + + select { + case <-requestCanceled: + case <-time.After(time.Second): + t.Fatal("request context was not canceled") + } +}