Repository navigation
Preserve inferred Content-Type in automatic HEAD responses #3249
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
anishpentyala
wants to merge
4
commits into
labstack:master
Choose a base branch
from
anishpentyala:fix/head-content-type
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
f3c356f
Preserve inferred Content-Type in automatic HEAD responses
anishpentyala 0e3904d
Test inferred HEAD Content-Type over HTTP
anishpentyala 04b3f6a
Run HEAD Content-Type inference after Before hooks
anishpentyala 8c31468
Test HEAD Content-Type after response hooks
anishpentyala File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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)) | ||
| } |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.