Skip to content

Commit 30b16e7

Browse files
committed
fix(middleware): reset ContentLength after gzip decompression
1 parent 6a390cb commit 30b16e7

3 files changed

Lines changed: 28 additions & 2 deletions

File tree

middleware/body_limit_test.go

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,31 @@ func TestBodyLimitConfig_ToMiddleware(t *testing.T) {
6868
assert.Equal(t, http.StatusRequestEntityTooLarge, he.StatusCode())
6969
}
7070

71+
func TestBodyLimitAfterDecompressUsesDecompressedSize(t *testing.T) {
72+
e := echo.New()
73+
body := "ok"
74+
gz, err := gzipString(body)
75+
assert.NoError(t, err)
76+
assert.Greater(t, len(gz), len(body))
77+
78+
req := httptest.NewRequest(http.MethodPost, "/", bytes.NewReader(gz))
79+
req.Header.Set(echo.HeaderContentEncoding, GZIPEncoding)
80+
rec := httptest.NewRecorder()
81+
c := e.NewContext(req, rec)
82+
83+
err = Decompress()(BodyLimit(int64(len(body)))(func(c *echo.Context) error {
84+
body, readErr := io.ReadAll(c.Request().Body)
85+
if readErr != nil {
86+
return readErr
87+
}
88+
return c.String(http.StatusOK, string(body))
89+
}))(c)
90+
91+
assert.NoError(t, err)
92+
assert.Equal(t, http.StatusOK, rec.Code)
93+
assert.Equal(t, body, rec.Body.String())
94+
}
95+
7196
func TestBodyLimitReader(t *testing.T) {
7297
hw := []byte("Hello, World!")
7398

middleware/decompress.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,7 @@ func (config DecompressConfig) ToMiddleware() (echo.MiddlewareFunc, error) {
120120
// -1 means explicitly unlimited (not recommended)
121121
c.Request().Body = gr
122122
}
123+
c.Request().ContentLength = -1
123124

124125
return next(c)
125126
}

middleware/decompress_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -215,8 +215,6 @@ func BenchmarkDecompress(b *testing.B) {
215215
e := echo.New()
216216
body := `{"name": "echo"}`
217217
gz, _ := gzipString(body)
218-
req := httptest.NewRequest(http.MethodPost, "/", strings.NewReader(string(gz)))
219-
req.Header.Set(echo.HeaderContentEncoding, GZIPEncoding)
220218

221219
h := Decompress()(func(c *echo.Context) error {
222220
c.Response().Write([]byte(body)) // For Content-Type sniffing
@@ -228,6 +226,8 @@ func BenchmarkDecompress(b *testing.B) {
228226

229227
for i := 0; i < b.N; i++ {
230228
// Decompress
229+
req := httptest.NewRequest(http.MethodPost, "/", bytes.NewReader(gz))
230+
req.Header.Set(echo.HeaderContentEncoding, GZIPEncoding)
231231
rec := httptest.NewRecorder()
232232
c := e.NewContext(req, rec)
233233
h(c)

0 commit comments

Comments
 (0)