Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions response.go
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,7 @@ type headResponseWriter struct {
status int
wroteStatus bool
bodyBytes int64
sniffBuf []byte
}

func (w *headResponseWriter) Header() http.Header {
Expand All @@ -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
}

Expand All @@ -282,6 +289,16 @@ func (w *headResponseWriter) Unwrap() http.ResponseWriter {
return w.rw
}

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(status) {
dst.Set(HeaderContentType, http.DetectContentType(w.sniffBuf))
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
}

func (w *headResponseWriter) commit() {
dst := w.rw.Header()
if w.wroteStatus &&
Expand All @@ -297,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
Expand Down
98 changes: 98 additions & 0 deletions response_head_hooks_test.go
Original file line number Diff line number Diff line change
@@ -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(), "<html>hello</html>")
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(), "<html>hello</html>")
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)
}
}
109 changes: 109 additions & 0 deletions response_head_sniff_test.go
Original file line number Diff line number Diff line change
@@ -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{"<!DOCTYPE html><html><body>hello</body></html>"}, 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><html>hello</html>"}, wantType: "text/html; charset=utf-8"},
{name: "leading empty write", chunks: []string{"", "<html>hello</html>"}, 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)), "<html>hello</html>"}, wantType: "text/plain; charset=utf-8"},
{name: "explicit type", chunks: []string{"<html>hello</html>"}, headers: http.Header{HeaderContentType: {"application/custom"}}, wantType: "application/custom"},
{name: "suppressed type", chunks: []string{"<html>hello</html>"}, headers: http.Header{HeaderContentType: nil}},
{name: "encoded content", chunks: []string{"<html>hello</html>"}, headers: http.Header{HeaderContentEncoding: {"gzip"}}},
{name: "empty encoding", chunks: []string{"<html>hello</html>"}, headers: http.Header{HeaderContentEncoding: {""}}, wantType: "text/html; charset=utf-8"},
{name: "no writes"},
{name: "empty write", chunks: []string{""}},
{name: "accepted", chunks: []string{"<html>hello</html>"}, 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("<html>ignored</html>"))
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("<html>ignored</html>"))
require.NoError(t, err)
w.commit()
require.Empty(t, rec.Header().Get(HeaderContentType))
}