forked from nytimes/gziphandler
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathgzip.go
65 lines (55 loc) · 1.04 KB
/
gzip.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package gzip
import (
"compress/gzip"
"fmt"
"io"
"sync"
"github.com/CAFxX/httpcompression/contrib/internal/utils"
)
const (
Encoding = "gzip"
DefaultCompression = gzip.DefaultCompression
)
type Options struct {
Level int
}
type compressor struct {
pool sync.Pool
opt Options
}
func New(opt Options) (*compressor, error) {
tw, err := gzip.NewWriterLevel(io.Discard, opt.Level)
if err != nil {
return nil, err
}
err = utils.CheckWriter(tw)
if err != nil {
return nil, fmt.Errorf("gzip: writer initialization: %w", err)
}
c := &compressor{opt: opt}
return c, nil
}
func (c *compressor) Get(w io.Writer) io.WriteCloser {
if gw, ok := c.pool.Get().(*gzipWriter); ok {
gw.Reset(w)
return gw
}
gw, err := gzip.NewWriterLevel(w, c.opt.Level)
if err != nil {
return utils.ErrorWriteCloser{Err: err}
}
return &gzipWriter{
Writer: gw,
c: c,
}
}
type gzipWriter struct {
*gzip.Writer
c *compressor
}
func (w *gzipWriter) Close() error {
err := w.Writer.Close()
w.Reset(nil)
w.c.pool.Put(w)
return err
}