-
Notifications
You must be signed in to change notification settings - Fork 55
/
gzip.go
53 lines (45 loc) · 886 Bytes
/
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
package gzip
import (
"bytes"
"compress/gzip"
"strings"
"github.com/sohaha/zlsgo/znet"
)
func Default() znet.HandlerFunc {
return New(Config{
CompressionLevel: 7,
PoolMaxSize: 1024,
MinContentLength: 1024,
})
}
func New(conf Config) znet.HandlerFunc {
pool := &poolCap{
c: make(chan *gzip.Writer, conf.PoolMaxSize),
l: conf.CompressionLevel,
}
return func(c *znet.Context) {
if !strings.Contains(c.GetHeader("Accept-Encoding"), "gzip") {
c.Next()
} else {
c.Next()
p := c.PrevContent()
if len(p.Content) < conf.MinContentLength {
return
}
g, err := pool.Get()
if err != nil {
return
}
defer pool.Put(g)
be := &bytes.Buffer{}
g.Reset(be)
_, err = g.Write(p.Content)
if err != nil {
return
}
_ = g.Flush()
c.SetHeader("Content-Encoding", "gzip")
c.Byte(p.Code.Load(), be.Bytes())
}
}
}