Skip to content

Commit

Permalink
fix handling of responses which are already compressed
Browse files Browse the repository at this point in the history
in my case by the origin server (reverse proxy), but I suppose other
middleware downstream could already be choosing to compress as well
  • Loading branch information
tj authored and jprobinson committed Sep 15, 2017
1 parent 4676616 commit 00f6462
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 3 deletions.
4 changes: 2 additions & 2 deletions gzip.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ func (w *GzipResponseWriter) Write(b []byte) (int, error) {
// If the global writes are bigger than the minSize and we're about to write
// a response containing a content type we want to handle, enable
// compression.
if len(w.buf) >= w.minSize && handleContentType(w.contentTypes, w) {
if len(w.buf) >= w.minSize && handleContentType(w.contentTypes, w) && w.Header().Get(contentEncoding) == "" {
err := w.startGzip()
if err != nil {
return 0, err
Expand Down Expand Up @@ -134,7 +134,7 @@ func (w *GzipResponseWriter) startGzip() error {
// Initialize the GZIP response.
w.init()

// Flush the buffer into the gzip response.
// Flush the buffer into the gzip reponse.
n, err := w.gw.Write(w.buf)

// This should never happen (per io.Writer docs), but if the write didn't
Expand Down
19 changes: 18 additions & 1 deletion gzip_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,17 @@ func TestGzipHandler(t *testing.T) {
assert.Equal(t, http.DetectContentType([]byte(testBody)), res3.Header().Get("Content-Type"))
}

func TestGzipHandlerAlreadyCompressed(t *testing.T) {
handler := newTestHandler(testBody)

req, _ := http.NewRequest("GET", "/gzipped", nil)
req.Header.Set("Accept-Encoding", "gzip")
res := httptest.NewRecorder()
handler.ServeHTTP(res, req)

assert.Equal(t, testBody, res.Body.String())
}

func TestNewGzipLevelHandler(t *testing.T) {
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
Expand Down Expand Up @@ -435,6 +446,12 @@ func runBenchmark(b *testing.B, req *http.Request, handler http.Handler) {

func newTestHandler(body string) http.Handler {
return GzipHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
io.WriteString(w, body)
switch r.URL.Path {
case "/gzipped":
w.Header().Set("Content-Encoding", "gzip")
io.WriteString(w, body)
default:
io.WriteString(w, body)
}
}))
}

0 comments on commit 00f6462

Please sign in to comment.