Skip to content
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

Drop accept-encoding header when supported #157

Merged
merged 3 commits into from
Jul 23, 2019
Merged
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
2 changes: 2 additions & 0 deletions compress.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,7 @@ func CompressHandlerLevel(h http.Handler, level int) http.Handler {
switch strings.TrimSpace(enc) {
case "gzip":
w.Header().Set("Content-Encoding", "gzip")
r.Header.Del("Accept-Encoding")
w.Header().Add("Vary", "Accept-Encoding")

gw, _ := gzip.NewWriterLevel(w, level)
Expand Down Expand Up @@ -111,6 +112,7 @@ func CompressHandlerLevel(h http.Handler, level int) http.Handler {
break L
case "deflate":
w.Header().Set("Content-Encoding", "deflate")
r.Header.Del("Accept-Encoding")
w.Header().Add("Vary", "Accept-Encoding")

fw, _ := flate.NewWriter(w, level)
Expand Down
65 changes: 65 additions & 0 deletions compress_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,71 @@ func TestCompressHandlerNoCompression(t *testing.T) {
}
}

func TestAcceptEncodingIsDropped(t *testing.T) {
tCases := []struct {
name,
compression,
expect string
isPresent bool
}{
{
"accept-encoding-gzip",
"gzip",
"",
false,
},
{
"accept-encoding-deflate",
"deflate",
"",
false,
},
{
"accept-encoding-gzip,deflate",
"gzip,deflate",
"",
false,
},
{
"accept-encoding-gzip,deflate,something",
"gzip,deflate,something",
"",
false,
},
{
"accept-encoding-unknown",
"unknown",
"unknown",
true,
},
}

for _, tCase := range tCases {
ch := CompressHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
acceptEnc := r.Header.Get("Accept-Encoding")
if acceptEnc == "" && tCase.isPresent {
t.Fatalf("%s: expected 'Accept-Encoding' header to be present but was not", tCase.name)
}
if acceptEnc != "" {
if !tCase.isPresent {
t.Fatalf("%s: expected 'Accept-Encoding' header to be dropped but was still present having value %q", tCase.name, acceptEnc)
}
if acceptEnc != tCase.expect {
t.Fatalf("%s: expected 'Accept-Encoding' to be %q but was %q", tCase.name, tCase.expect, acceptEnc)
}
}
}))

w := httptest.NewRecorder()
ch.ServeHTTP(w, &http.Request{
Method: "GET",
Header: http.Header{
"Accept-Encoding": []string{tCase.compression},
},
})
}
}

func TestCompressHandlerGzip(t *testing.T) {
w := httptest.NewRecorder()
compressedRequest(w, "gzip")
Expand Down