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

[gzhttp] Add supported decompress request body #1002

Merged
merged 9 commits into from
Sep 11, 2024
12 changes: 12 additions & 0 deletions gzhttp/compress.go
Original file line number Diff line number Diff line change
Expand Up @@ -464,6 +464,12 @@ 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) {
if readerGzipBody, err := gzip.NewReader(r.Body); err == nil {
r.Body = io.NopCloser(readerGzipBody)
mirecl marked this conversation as resolved.
Show resolved Hide resolved
}
mirecl marked this conversation as resolved.
Show resolved Hide resolved
}

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

// contentGzip returns true if the given HTTP request indicates that it gzipped.
func contentGzip(r *http.Request) bool {
// See more detail in `acceptsGzip`
return r.Method != http.MethodHead && parseEncodingGzip(r.Header.Get(contentEncoding)) > 0
mirecl marked this conversation as resolved.
Show resolved Hide resolved
}

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

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

// 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
Loading