Use pool for buffer

This commit is contained in:
Ingo Oppermann
2022-09-28 14:53:58 +02:00
parent 7d38416239
commit 6288b620df

View File

@@ -35,7 +35,7 @@ type gzipResponseWriter struct {
wroteBody bool wroteBody bool
minLength int minLength int
minLengthExceeded bool minLengthExceeded bool
buffer bytes.Buffer buffer *bytes.Buffer
code int code int
} }
@@ -101,6 +101,7 @@ func NewWithConfig(config Config) echo.MiddlewareFunc {
} }
pool := gzipPool(config) pool := gzipPool(config)
bpool := bufferPool()
return func(next echo.HandlerFunc) echo.HandlerFunc { return func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error { return func(c echo.Context) error {
@@ -119,7 +120,11 @@ func NewWithConfig(config Config) echo.MiddlewareFunc {
} }
rw := res.Writer rw := res.Writer
w.Reset(rw) w.Reset(rw)
grw := &gzipResponseWriter{Writer: w, ResponseWriter: rw, minLength: config.MinLength}
buf := bpool.Get().(*bytes.Buffer)
buf.Reset()
grw := &gzipResponseWriter{Writer: w, ResponseWriter: rw, minLength: config.MinLength, buffer: buf}
defer func() { defer func() {
if !grw.wroteBody { if !grw.wroteBody {
@@ -141,6 +146,7 @@ func NewWithConfig(config Config) echo.MiddlewareFunc {
w.Reset(io.Discard) w.Reset(io.Discard)
} }
w.Close() w.Close()
bpool.Put(buf)
pool.Put(w) pool.Put(w)
}() }()
@@ -232,3 +238,12 @@ func gzipPool(config Config) sync.Pool {
}, },
} }
} }
func bufferPool() sync.Pool {
return sync.Pool{
New: func() interface{} {
b := &bytes.Buffer{}
return b
},
}
}