From d9c2d0132ee115de34064a5c424f9dd4a7b7217a Mon Sep 17 00:00:00 2001 From: Will McCutchen <will@mccutch.org> Date: Sun, 4 Oct 2020 11:20:54 -0400 Subject: [PATCH] Fix handling of HEAD requests for streaming responses --- httpbin/handlers_test.go | 23 +++++++++++++++++++++++ httpbin/middleware.go | 4 ++-- 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/httpbin/handlers_test.go b/httpbin/handlers_test.go index 7873586..aa67e1f 100644 --- a/httpbin/handlers_test.go +++ b/httpbin/handlers_test.go @@ -1604,6 +1604,29 @@ func TestDrip(t *testing.T) { assertStatusCode(t, w, test.code) }) } + + t.Run("ensure HEAD request works with streaming responses", func(t *testing.T) { + srv := httptest.NewServer(handler) + defer srv.Close() + + resp, err := http.Head(srv.URL + "/drip?duration=900ms&delay=100ms") + if err != nil { + t.Fatalf("unexpected error: %s", err) + } + defer resp.Body.Close() + + body, err := ioutil.ReadAll(resp.Body) + if err != nil { + t.Fatalf("error reading response body: %s", err) + } + + if resp.StatusCode != http.StatusOK { + t.Fatalf("expected HTTP 200 OK rsponse, got %d", resp.StatusCode) + } + if bodySize := len(body); bodySize > 0 { + t.Fatalf("expected empty body from HEAD request, bot: %s", string(body)) + } + }) } func TestRange(t *testing.T) { diff --git a/httpbin/middleware.go b/httpbin/middleware.go index e35a5a9..5186789 100644 --- a/httpbin/middleware.go +++ b/httpbin/middleware.go @@ -61,7 +61,7 @@ func limitRequestSize(maxSize int64, h http.Handler) http.Handler { // headResponseWriter implements http.ResponseWriter in order to discard the // body of the response type headResponseWriter struct { - http.ResponseWriter + *metaResponseWriter } func (hw *headResponseWriter) Write(b []byte) (int, error) { @@ -72,7 +72,7 @@ func (hw *headResponseWriter) Write(b []byte) (int, error) { func autohead(h http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method == "HEAD" { - w = &headResponseWriter{w} + w = &headResponseWriter{&metaResponseWriter{w: w}} } h.ServeHTTP(w, r) }) -- GitLab