From c8802fecc01659e06441d233625b9c0f7c8a3ca1 Mon Sep 17 00:00:00 2001 From: caixw Date: Sat, 3 Feb 2024 10:40:43 +0800 Subject: [PATCH] =?UTF-8?q?fix(compressor):=20=E4=BF=AE=E6=AD=A3=20NewGzip?= =?UTF-8?q?=20=E7=9A=84=E5=8F=82=E6=95=B0=20level=20=E6=9C=AA=E4=BD=BF?= =?UTF-8?q?=E7=94=A8=E7=9A=84=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- compressor/compressor.go | 27 +++++++++++++++++++-------- web.go | 2 +- 2 files changed, 20 insertions(+), 9 deletions(-) diff --git a/compressor/compressor.go b/compressor/compressor.go index 2daae298..278871b9 100644 --- a/compressor/compressor.go +++ b/compressor/compressor.go @@ -58,7 +58,6 @@ var ( } return r }} - gzipWriters = &sync.Pool{New: func() any { return gzip.NewWriter(nil) }} // deflate deflateReaders = &sync.Pool{New: func() any { @@ -90,7 +89,9 @@ type ( width int } - gzipCompressor struct{} + gzipCompressor struct { + writers *sync.Pool + } deflateCompressor struct { dict []byte @@ -183,11 +184,21 @@ func (c *lzwCompressor) NewEncoder(w io.Writer) (io.WriteCloser, error) { } // NewGzip 声明基于 gzip 的压缩算法 -func NewGzip(level int) Compressor { return &gzipCompressor{} } +func NewGzip(level int) Compressor { + return &gzipCompressor{ + writers: &sync.Pool{New: func() any { + w, err := gzip.NewWriterLevel(nil, level) + if err != nil { + panic(err) + } + return w + }}, + } +} -func (c *gzipCompressor) Name() string { return "gzip" } +func (c gzipCompressor) Name() string { return "gzip" } -func (c *gzipCompressor) NewDecoder(r io.Reader) (io.ReadCloser, error) { +func (c gzipCompressor) NewDecoder(r io.Reader) (io.ReadCloser, error) { rr := gzipReaders.Get().(*gzip.Reader) if err := rr.Reset(r); err != nil { return nil, err @@ -195,10 +206,10 @@ func (c *gzipCompressor) NewDecoder(r io.Reader) (io.ReadCloser, error) { return wrapDecoder(rr, func() { gzipReaders.Put(rr) }), nil } -func (c *gzipCompressor) NewEncoder(w io.Writer) (io.WriteCloser, error) { - ww := gzipWriters.Get().(*gzip.Writer) +func (c gzipCompressor) NewEncoder(w io.Writer) (io.WriteCloser, error) { + ww := c.writers.Get().(*gzip.Writer) ww.Reset(w) - return wrapEncoder(ww, func() { gzipWriters.Put(ww) }), nil + return wrapEncoder(ww, func() { c.writers.Put(ww) }), nil } // NewDeflate 声明基于 deflate 的压缩算法 diff --git a/web.go b/web.go index 52ecff47..c3c1a163 100644 --- a/web.go +++ b/web.go @@ -82,7 +82,7 @@ func NewLocaleError(format string, v ...any) error { return localeutil.Error(for // NewError 用 HTTP 状态码包装一个错误信息 // // status 表示 HTTP 状态码; -// err 被包装的错误信息,如果所有错误都是空值,将会 panic; +// err 被包装的错误信息,如果是空值,将会 panic; // // 此方法返回的错误,在 [Context.Error] 会被识别且按指定的状态码输出。 func NewError(status int, err error) error { return errs.NewError(status, err) }