Skip to content

Commit

Permalink
fix(compressor): 修正 NewGzip 的参数 level 未使用的问题
Browse files Browse the repository at this point in the history
  • Loading branch information
caixw committed Feb 3, 2024
1 parent 663345e commit c8802fe
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 9 deletions.
27 changes: 19 additions & 8 deletions compressor/compressor.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,6 @@ var (
}
return r
}}
gzipWriters = &sync.Pool{New: func() any { return gzip.NewWriter(nil) }}

// deflate
deflateReaders = &sync.Pool{New: func() any {
Expand Down Expand Up @@ -90,7 +89,9 @@ type (
width int
}

gzipCompressor struct{}
gzipCompressor struct {
writers *sync.Pool
}

deflateCompressor struct {
dict []byte
Expand Down Expand Up @@ -183,22 +184,32 @@ 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
}
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 的压缩算法
Expand Down
2 changes: 1 addition & 1 deletion web.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) }

0 comments on commit c8802fe

Please sign in to comment.