Skip to content

Commit

Permalink
[gzhttp] Add supported decompress request body
Browse files Browse the repository at this point in the history
  • Loading branch information
mirecl committed Sep 10, 2024
1 parent 13c1244 commit 7fa5377
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
14 changes: 14 additions & 0 deletions gzhttp/compress.go
Original file line number Diff line number Diff line change
Expand Up @@ -464,6 +464,15 @@ func NewWrapper(opts ...option) (func(http.Handler) http.HandlerFunc, error) {
return func(h http.Handler) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Add(vary, acceptEncoding)
if contentGzip(r) {
readerGzipBody, err := gzip.NewReader(r.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
r.Body = io.NopCloser(readerGzipBody)
}

if acceptsGzip(r) {
gw := grwPool.Get().(*GzipResponseWriter)
*gw = GzipResponseWriter{
Expand Down Expand Up @@ -752,6 +761,11 @@ func RandomJitter(n, buffer int, paranoid bool) option {
}
}

func contentGzip(r *http.Request) bool {
// See more detail in `acceptsGzip`
return r.Method != http.MethodHead && parseEncodingGzip(r.Header.Get(contentEncoding)) > 0
}

// acceptsGzip returns true if the given HTTP request indicates that it will
// accept a gzipped response.
func acceptsGzip(r *http.Request) bool {
Expand Down
28 changes: 28 additions & 0 deletions gzhttp/compress_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,34 @@ func TestMustNewGzipHandler(t *testing.T) {
handler.ServeHTTP(res3, req3)

assertEqual(t, http.DetectContentType([]byte(testBody)), res3.Header().Get("Content-Type"))

// send not compress request body

req4, _ := http.NewRequest("POST", "/whatever", bytes.NewBuffer(testBody))
req4.Header.Set("Content-Encoding", "gzip")
resp4 := httptest.NewRecorder()
handler.ServeHTTP(resp4, req4)
res4 := resp4.Result()

assertEqual(t, 400, res4.StatusCode)

// send compress request body

var b bytes.Buffer
writerGzip := gzip.NewWriter(&b)
writerGzip.Write(testBody)
writerGzip.Close()

req5, _ := http.NewRequest("POST", "/whatever", &b)
req5.Header.Set("Content-Encoding", "gzip")
resp5 := httptest.NewRecorder()
handler.ServeHTTP(resp5, req5)
res5 := resp5.Result()

assertEqual(t, 200, res5.StatusCode)

body, _ := io.ReadAll(res5.Body)
assertEqual(t, len(testBody), len(body))
}

func TestGzipHandlerSmallBodyNoCompression(t *testing.T) {
Expand Down

0 comments on commit 7fa5377

Please sign in to comment.