Skip to content

Commit

Permalink
stream decompression instead of buffering
Browse files Browse the repository at this point in the history
  • Loading branch information
davidmdm committed Nov 4, 2021
1 parent d604704 commit 713187f
Showing 1 changed file with 39 additions and 23 deletions.
62 changes: 39 additions & 23 deletions middleware/decompress.go
Expand Up @@ -86,35 +86,51 @@ func DecompressWithConfig(config DecompressConfig) echo.MiddlewareFunc {
if config.Skipper(c) {
return next(c)
}
switch c.Request().Header.Get(echo.HeaderContentEncoding) {
case GZIPEncoding:
b := c.Request().Body

i := pool.Get()
gr, ok := i.(*gzip.Reader)
if !ok {
return echo.NewHTTPError(http.StatusInternalServerError, i.(error).Error())
}

if err := gr.Reset(b); err != nil {
pool.Put(gr)
if err == io.EOF { //ignore if body is empty
return next(c)
}
return err
}
var buf bytes.Buffer
io.Copy(&buf, gr)
if c.Request().Header.Get(echo.HeaderContentEncoding) != GZIPEncoding {
return next(c)
}

gr.Close()
pool.Put(gr)
b := c.Request().Body

i := pool.Get()
gr, ok := i.(*gzip.Reader)
if !ok {
return echo.NewHTTPError(http.StatusInternalServerError, i.(error).Error())
}

b.Close() // http.Request.Body is closed by the Server, but because we are replacing it, it must be closed here
if err := gr.Reset(b); err != nil {
pool.Put(gr)
if err == io.EOF { //ignore if body is empty
return next(c)
}
return err
}

r := ioutil.NopCloser(&buf)
c.Request().Body = r
c.Request().Body = readCloserCustom{
gr,
func() error {
gr.Close()
b.Close()
pool.Put(gr)
return nil
},
}

return next(c)
}

}
}

type readCloserCustom struct {
io.Reader
closeFunc func() error
}

func (rc readCloserCustom) Close() error {
if rc.closeFunc == nil {
return nil
}
return rc.closeFunc()
}

0 comments on commit 713187f

Please sign in to comment.