Skip to content

Commit

Permalink
Fix GZip compression
Browse files Browse the repository at this point in the history
  • Loading branch information
z4kn4fein committed Nov 29, 2023
1 parent 8b7d63b commit d6f1e1d
Show file tree
Hide file tree
Showing 5 changed files with 73 additions and 100 deletions.
2 changes: 1 addition & 1 deletion sdk/user_agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import (
"net/http"
)

const proxyVersion = "0.2.3"
const proxyVersion = "0.2.4"

type userAgentInterceptor struct {
http.RoundTripper
Expand Down
19 changes: 10 additions & 9 deletions web/mware/compress.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,11 @@ func GZip(next http.HandlerFunc) http.HandlerFunc {
w.Header().Set("Vary", "Accept-Encoding")
writer := pool.Get().(*gzip.Writer)
writer.Reset(w)
gz := gzipWriter{writer: writer, ResponseWriter: w}
defer gz.close()
next(&gz, r)
gz := &gzipWriter{writer: writer, ResponseWriter: w}
defer func() {
_ = gz.Close()
}()
next(gz, r)
} else {
next(w, r)
}
Expand All @@ -47,18 +49,17 @@ func (w *gzipWriter) Write(b []byte) (int, error) {
if !w.headersDone {
w.WriteHeader(http.StatusOK)
}
i, e := w.writer.Write(b)
_ = w.writer.Flush()
return i, e
return w.writer.Write(b)
}

func (w *gzipWriter) Flush() {
_ = w.writer.Flush()
if flusher, ok := w.ResponseWriter.(http.Flusher); ok {
flusher.Flush()
}
}

func (w *gzipWriter) close() {
w.writer.Reset(io.Discard)
pool.Put(w.writer)
func (w *gzipWriter) Close() error {
defer pool.Put(w.writer)
return w.writer.Close()
}
17 changes: 6 additions & 11 deletions web/mware/compress_test.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package mware

import (
"bytes"
"compress/gzip"
"github.com/stretchr/testify/assert"
"io"
Expand All @@ -15,25 +14,21 @@ func TestGZip(t *testing.T) {
_, _ = writer.Write([]byte("test"))
})
srv := httptest.NewServer(handler)
client := http.Client{}

t.Run("with gzip", func(t *testing.T) {
req, _ := http.NewRequest(http.MethodGet, srv.URL, http.NoBody)
req.Header.Set("Accept-Encoding", "gzip")
resp, _ := client.Do(req)
resp, _ := http.DefaultClient.Do(req)
assert.Equal(t, http.StatusOK, resp.StatusCode)
body, _ := io.ReadAll(resp.Body)
_ = resp.Body.Close()
assert.Equal(t, "gzip", resp.Header.Get("Content-Encoding"))
var buf bytes.Buffer
wr := gzip.NewWriter(&buf)
_, _ = wr.Write([]byte("test"))
_ = wr.Flush()
assert.Equal(t, buf.Bytes(), body)
gzipReader, err := gzip.NewReader(resp.Body)
assert.NoError(t, err)
body, _ := io.ReadAll(gzipReader)
assert.Equal(t, "test", string(body))
})
t.Run("without gzip", func(t *testing.T) {
req, _ := http.NewRequest(http.MethodGet, srv.URL, http.NoBody)
resp, _ := client.Do(req)
resp, _ := http.DefaultClient.Do(req)
assert.Equal(t, http.StatusOK, resp.StatusCode)
body, _ := io.ReadAll(resp.Body)
_ = resp.Body.Close()
Expand Down
Loading

0 comments on commit d6f1e1d

Please sign in to comment.