Skip to content

Commit

Permalink
Drop accept-encoding header when supported (#157)
Browse files Browse the repository at this point in the history
* Verify that supported Accept-Encoding header are dropped

* Drop accept-encoding header when supported

This prevents following handlers from encoding the request again since
we dropped the intention to do this.

Fixes #153

* Do not use subtests to be compatible with Go <1.7
  • Loading branch information
klingtnet authored and elithrar committed Jul 23, 2019
1 parent 9a606a4 commit 7a35d4c
Show file tree
Hide file tree
Showing 2 changed files with 67 additions and 0 deletions.
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

0 comments on commit 7a35d4c

Please sign in to comment.