From f3c356fafdaae59aae7fb477a8d38a0e40059590 Mon Sep 17 00:00:00 2001 From: Anish Pentyala Date: Wed, 25 Nov 2026 11:32:23 -0800 Subject: [PATCH 1/4] Preserve inferred Content-Type in automatic HEAD responses --- response.go | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/response.go b/response.go index e6adea77c..cc9c6ee2e 100644 --- a/response.go +++ b/response.go @@ -240,6 +240,7 @@ type headResponseWriter struct { status int wroteStatus bool bodyBytes int64 + sniffBuf []byte } func (w *headResponseWriter) Header() http.Header { @@ -266,6 +267,12 @@ func (w *headResponseWriter) Write(b []byte) (int, error) { w.WriteHeader(http.StatusOK) } w.bodyBytes += int64(len(b)) + // net/http normally infers the type from the first 512 body bytes. + // Retain only that prefix because HEAD discards writes before they + // reach the transport. + if remaining := 512 - len(w.sniffBuf); remaining > 0 { + w.sniffBuf = append(w.sniffBuf, b[:min(len(b), remaining)]...) + } return len(b), nil } @@ -284,6 +291,12 @@ func (w *headResponseWriter) Unwrap() http.ResponseWriter { func (w *headResponseWriter) commit() { dst := w.rw.Header() + _, hasContentType := dst[HeaderContentType] + if !hasContentType && len(w.sniffBuf) > 0 && + dst.Get(HeaderContentEncoding) == "" && dst.Get("Transfer-Encoding") == "" && + !statusMustNotHaveBody(w.status) { + dst.Set(HeaderContentType, http.DetectContentType(w.sniffBuf)) + } if w.wroteStatus && dst.Get(HeaderContentLength) == "" && dst.Get("Transfer-Encoding") == "" && From 0e3904dea39c06be4dc6fe07ad8c2320251c00ab Mon Sep 17 00:00:00 2001 From: Anish Pentyala Date: Wed, 25 Nov 2026 11:33:00 -0800 Subject: [PATCH 2/4] Test inferred HEAD Content-Type over HTTP --- response_head_sniff_test.go | 109 ++++++++++++++++++++++++++++++++++++ 1 file changed, 109 insertions(+) create mode 100644 response_head_sniff_test.go diff --git a/response_head_sniff_test.go b/response_head_sniff_test.go new file mode 100644 index 000000000..3c1ed5adb --- /dev/null +++ b/response_head_sniff_test.go @@ -0,0 +1,109 @@ +// SPDX-License-Identifier: MIT +// SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors + +package echo + +import ( + "bytes" + "io" + "net/http" + "net/http/httptest" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestRouterAutoHandleHEAD_SniffContentType(t *testing.T) { + for _, tc := range []struct { + name string + chunks []string + headers http.Header + status int + wantType string + }{ + {name: "HTML", chunks: []string{"hello"}, wantType: "text/html; charset=utf-8"}, + {name: "plain text", chunks: []string{"hello world"}, wantType: "text/plain; charset=utf-8"}, + {name: "split HTML", chunks: []string{"<", "!DOC", "TYPE html>hello"}, wantType: "text/html; charset=utf-8"}, + {name: "leading empty write", chunks: []string{"", "hello"}, wantType: "text/html; charset=utf-8"}, + {name: "binary", chunks: []string{string([]byte{0, 1, 2, 3})}, wantType: "application/octet-stream"}, + {name: "bounded prefix", chunks: []string{string(bytes.Repeat([]byte(" "), 512)), "hello"}, wantType: "text/plain; charset=utf-8"}, + {name: "explicit type", chunks: []string{"hello"}, headers: http.Header{HeaderContentType: {"application/custom"}}, wantType: "application/custom"}, + {name: "suppressed type", chunks: []string{"hello"}, headers: http.Header{HeaderContentType: nil}}, + {name: "encoded content", chunks: []string{"hello"}, headers: http.Header{HeaderContentEncoding: {"gzip"}}}, + {name: "empty encoding", chunks: []string{"hello"}, headers: http.Header{HeaderContentEncoding: {""}}, wantType: "text/html; charset=utf-8"}, + {name: "no writes"}, + {name: "empty write", chunks: []string{""}}, + {name: "accepted", chunks: []string{"hello"}, status: http.StatusAccepted, wantType: "text/html; charset=utf-8"}, + } { + t.Run(tc.name, func(t *testing.T) { + e := NewWithConfig(Config{Router: NewRouter(RouterConfig{AutoHandleHEAD: true})}) + e.GET("/", func(c *Context) error { + for k, v := range tc.headers { + c.Response().Header()[k] = v + } + if tc.status != 0 { + c.Response().WriteHeader(tc.status) + } + for _, chunk := range tc.chunks { + if _, err := io.WriteString(c.Response(), chunk); err != nil { + return err + } + } + return nil + }) + server := httptest.NewServer(e) + defer server.Close() + client := server.Client() + client.Transport.(*http.Transport).DisableCompression = true + for _, method := range []string{http.MethodGet, http.MethodHead} { + req, err := http.NewRequest(method, server.URL, nil) + require.NoError(t, err) + res, err := client.Do(req) + require.NoError(t, err) + body, err := io.ReadAll(res.Body) + require.NoError(t, err) + require.NoError(t, res.Body.Close()) + require.Equal(t, tc.wantType, res.Header.Get(HeaderContentType), method) + require.Equal(t, max(http.StatusOK, tc.status), res.StatusCode, method) + if method == http.MethodHead { + require.Empty(t, body) + } + } + }) + } +} + +func TestHeadResponseWriter_SniffPrefixBounded(t *testing.T) { + rec := httptest.NewRecorder() + w := &headResponseWriter{rw: rec} + payload := bytes.Repeat([]byte("x"), 1<<20) + for range 3 { + n, err := w.Write(payload) + require.NoError(t, err) + require.Equal(t, len(payload), n) + } + require.Len(t, w.sniffBuf, 512) + require.Equal(t, int64(3*len(payload)), w.bodyBytes) + require.Empty(t, rec.Body.String()) +} + +func TestHeadResponseWriter_SniffSkipsBodylessStatusAndTransferEncoding(t *testing.T) { + for _, status := range []int{http.StatusSwitchingProtocols, http.StatusNoContent, http.StatusResetContent, http.StatusNotModified} { + t.Run(http.StatusText(status), func(t *testing.T) { + rec := httptest.NewRecorder() + w := &headResponseWriter{rw: rec} + w.WriteHeader(status) + _, err := w.Write([]byte("ignored")) + require.NoError(t, err) + w.commit() + require.Empty(t, rec.Header().Get(HeaderContentType)) + }) + } + rec := httptest.NewRecorder() + rec.Header().Set("Transfer-Encoding", "chunked") + w := &headResponseWriter{rw: rec} + _, err := w.Write([]byte("ignored")) + require.NoError(t, err) + w.commit() + require.Empty(t, rec.Header().Get(HeaderContentType)) +} From 04b3f6ad1872ba59f2a4c03017d2903c70694360 Mon Sep 17 00:00:00 2001 From: Anish Pentyala Date: Wed, 25 Nov 2026 14:06:15 -0800 Subject: [PATCH 3/4] Run HEAD Content-Type inference after Before hooks --- response.go | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/response.go b/response.go index cc9c6ee2e..c38fc6bf1 100644 --- a/response.go +++ b/response.go @@ -289,14 +289,18 @@ func (w *headResponseWriter) Unwrap() http.ResponseWriter { return w.rw } -func (w *headResponseWriter) commit() { +func (w *headResponseWriter) sniffContentType(status int) { dst := w.rw.Header() _, hasContentType := dst[HeaderContentType] if !hasContentType && len(w.sniffBuf) > 0 && dst.Get(HeaderContentEncoding) == "" && dst.Get("Transfer-Encoding") == "" && - !statusMustNotHaveBody(w.status) { + !statusMustNotHaveBody(status) { dst.Set(HeaderContentType, http.DetectContentType(w.sniffBuf)) } +} + +func (w *headResponseWriter) commit() { + dst := w.rw.Header() if w.wroteStatus && dst.Get(HeaderContentLength) == "" && dst.Get("Transfer-Encoding") == "" && @@ -310,6 +314,11 @@ func (w *headResponseWriter) commit() { // Reset it here so *Response.WriteHeader can fire beforeFuncs and reach the transport. if r, err := UnwrapResponse(w.rw); err == nil { r.Committed = false + // Sniff after application Before hooks, just as net/http does for GET. + // The hook also observes any final status chosen by those callbacks. + r.Before(func() { w.sniffContentType(r.Status) }) + } else { + w.sniffContentType(w.status) } w.rw.WriteHeader(w.status) // Fire After hooks on the underlying *Response so that middleware such as From 8c314686a05d21e78f991f4699ab49a6fcc7571b Mon Sep 17 00:00:00 2001 From: Anish Pentyala Date: Wed, 25 Nov 2026 14:06:35 -0800 Subject: [PATCH 4/4] Test HEAD Content-Type after response hooks --- response_head_hooks_test.go | 98 +++++++++++++++++++++++++++++++++++++ 1 file changed, 98 insertions(+) create mode 100644 response_head_hooks_test.go diff --git a/response_head_hooks_test.go b/response_head_hooks_test.go new file mode 100644 index 000000000..5c46364ed --- /dev/null +++ b/response_head_hooks_test.go @@ -0,0 +1,98 @@ +// SPDX-License-Identifier: MIT +// SPDX-FileCopyrightText: © 2015 LabStack LLC and Echo contributors + +package echo + +import ( + "io" + "net/http" + "net/http/httptest" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestRouterAutoHandleHEAD_BeforeSniffContentType(t *testing.T) { + for _, tc := range []struct { + name string + hook func(*Response) + wantType string + wantEncoding string + wantStatus int + }{ + {name: "conditional default", hook: func(r *Response) { + if r.Header().Get(HeaderContentType) == "" { + r.Header().Set(HeaderContentType, "application/custom") + } + }, wantType: "application/custom"}, + {name: "unconditional override", hook: func(r *Response) { r.Header().Set(HeaderContentType, "application/custom") }, wantType: "application/custom"}, + {name: "suppression", hook: func(r *Response) { r.Header()[HeaderContentType] = nil }}, + {name: "encoding", hook: func(r *Response) { r.Header().Set(HeaderContentEncoding, "gzip") }, wantEncoding: "gzip"}, + {name: "no type change", hook: func(r *Response) { r.Header().Set("X-Hook", "ran") }, wantType: "text/html; charset=utf-8"}, + {name: "bodyless status", hook: func(r *Response) { r.Status = http.StatusNoContent }, wantStatus: http.StatusNoContent}, + } { + t.Run(tc.name, func(t *testing.T) { + e := NewWithConfig(Config{Router: NewRouter(RouterConfig{AutoHandleHEAD: true})}) + calls := 0 + e.GET("/", func(c *Context) error { + res, err := UnwrapResponse(c.Response()) + if err != nil { + return err + } + res.Before(func() { calls++; tc.hook(res) }) + _, err = io.WriteString(c.Response(), "hello") + return err + }) + server := httptest.NewServer(e) + defer server.Close() + client := server.Client() + client.Transport.(*http.Transport).DisableCompression = true + for i, method := range []string{http.MethodGet, http.MethodHead} { + req, err := http.NewRequest(method, server.URL, nil) + require.NoError(t, err) + res, err := client.Do(req) + require.NoError(t, err) + body, err := io.ReadAll(res.Body) + require.NoError(t, err) + require.NoError(t, res.Body.Close()) + require.Equal(t, tc.wantType, res.Header.Get(HeaderContentType), method) + require.Equal(t, tc.wantEncoding, res.Header.Get(HeaderContentEncoding), method) + require.Equal(t, max(http.StatusOK, tc.wantStatus), res.StatusCode, method) + require.Equal(t, i+1, calls, method) + if method == http.MethodHead { + require.Empty(t, body) + } + } + }) + } +} + +func TestRouterAutoHandleHEAD_BeforeHookOrder(t *testing.T) { + e := NewWithConfig(Config{Router: NewRouter(RouterConfig{AutoHandleHEAD: true})}) + e.GET("/", func(c *Context) error { + res, err := UnwrapResponse(c.Response()) + if err != nil { + return err + } + res.Before(func() { res.Header().Set(HeaderContentType, "application/first") }) + res.Before(func() { + if res.Header().Get(HeaderContentType) == "application/first" { + res.Header().Set(HeaderContentType, "application/second") + } + }) + _, err = io.WriteString(c.Response(), "hello") + return err + }) + server := httptest.NewServer(e) + defer server.Close() + for _, method := range []string{http.MethodGet, http.MethodHead} { + req, err := http.NewRequest(method, server.URL, nil) + require.NoError(t, err) + res, err := server.Client().Do(req) + require.NoError(t, err) + _, err = io.Copy(io.Discard, res.Body) + require.NoError(t, err) + require.NoError(t, res.Body.Close()) + require.Equal(t, "application/second", res.Header.Get(HeaderContentType), method) + } +}