Skip to content

Commit 77e02f0

Browse files
committed
simply gzip.Reader pool
1 parent 71f28fd commit 77e02f0

File tree

1 file changed

+7
-26
lines changed

1 file changed

+7
-26
lines changed

middleware/decompress.go

+7-26
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,8 @@
11
package middleware
22

33
import (
4-
"bytes"
54
"compress/gzip"
65
"io"
7-
"io/ioutil"
86
"net/http"
97
"sync"
108

@@ -43,26 +41,7 @@ type DefaultGzipDecompressPool struct {
4341
}
4442

4543
func (d *DefaultGzipDecompressPool) gzipDecompressPool() sync.Pool {
46-
return sync.Pool{
47-
New: func() interface{} {
48-
// create with an empty reader (but with GZIP header)
49-
w, err := gzip.NewWriterLevel(ioutil.Discard, gzip.BestSpeed)
50-
if err != nil {
51-
return err
52-
}
53-
54-
b := new(bytes.Buffer)
55-
w.Reset(b)
56-
w.Flush()
57-
w.Close()
58-
59-
r, err := gzip.NewReader(bytes.NewReader(b.Bytes()))
60-
if err != nil {
61-
return err
62-
}
63-
return r
64-
},
65-
}
44+
return sync.Pool{New: func() interface{} { return new(gzip.Reader) }}
6645
}
6746

6847
//Decompress decompresses request body based if content encoding type is set to "gzip" with default config
@@ -82,6 +61,7 @@ func DecompressWithConfig(config DecompressConfig) echo.MiddlewareFunc {
8261

8362
return func(next echo.HandlerFunc) echo.HandlerFunc {
8463
pool := config.GzipDecompressPool.gzipDecompressPool()
64+
8565
return func(c echo.Context) error {
8666
if config.Skipper(c) {
8767
return next(c)
@@ -93,13 +73,13 @@ func DecompressWithConfig(config DecompressConfig) echo.MiddlewareFunc {
9373

9474
i := pool.Get()
9575
gr, ok := i.(*gzip.Reader)
96-
if !ok {
76+
if !ok || gr == nil {
9777
return echo.NewHTTPError(http.StatusInternalServerError, i.(error).Error())
9878
}
9979
defer pool.Put(gr)
100-
defer gr.Close()
10180

10281
b := c.Request().Body
82+
defer b.Close()
10383

10484
if err := gr.Reset(b); err != nil {
10585
if err == io.EOF { //ignore if body is empty
@@ -108,11 +88,12 @@ func DecompressWithConfig(config DecompressConfig) echo.MiddlewareFunc {
10888
return err
10989
}
11090

111-
defer b.Close()
91+
// only Close gzip reader if it was set to a proper gzip source otherwise it will panic on close.
92+
defer gr.Close()
93+
11294
c.Request().Body = gr
11395

11496
return next(c)
11597
}
116-
11798
}
11899
}

0 commit comments

Comments
 (0)