-
Notifications
You must be signed in to change notification settings - Fork 5
/
gzip.go
112 lines (90 loc) · 1.67 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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package pgo2
import (
"compress/gzip"
"io"
"io/ioutil"
"net/http"
"path/filepath"
"strings"
"sync"
"github.com/pinguo/pgo2/iface"
)
// Gzip gzip compression plugin
func NewGzip() *Gzip {
gzipObj := &Gzip{}
gzipObj.pool.New = func() interface{} {
return &gzipWrite{writer: gzip.NewWriter(ioutil.Discard)}
}
return gzipObj
}
type Gzip struct {
pool sync.Pool
}
func (g *Gzip) HandleRequest(ctx iface.IContext) {
ae := ctx.Header("Accept-Encoding", "")
if !strings.Contains(ae, "gzip") {
return
}
ext := filepath.Ext(ctx.Path())
switch strings.ToLower(ext) {
case ".png", ".gif", ".jpeg", ".jpg", ".ico":
return
}
gw := g.pool.Get().(*gzipWrite)
gw.reset(ctx)
defer func() {
gw.finish()
g.pool.Put(gw)
}()
ctx.Next()
}
type gzipWrite struct {
http.ResponseWriter
writer *gzip.Writer
ctx iface.IContext
size int
}
func (g *gzipWrite) reset(ctx iface.IContext) {
g.ResponseWriter = ctx.Output()
g.ctx = ctx
g.size = -1
ctx.SetOutput(g)
}
func (g *gzipWrite) finish() {
if g.size > 0 {
g.writer.Close()
}
}
func (g *gzipWrite) start() {
if g.size == -1 {
g.size = 0
g.writer.Reset(g.ResponseWriter)
g.ctx.SetHeader("Content-Encoding", "gzip")
}
}
func (g *gzipWrite) Flush() {
if g.size > 0 {
g.writer.Flush()
}
if flusher, ok := g.ResponseWriter.(http.Flusher); ok {
flusher.Flush()
}
}
func (g *gzipWrite) Write(data []byte) (n int, e error) {
if len(data) == 0 {
return 0, nil
}
g.start()
n, e = g.writer.Write(data)
g.size += n
return
}
func (g *gzipWrite) WriteString(data string) (n int, e error) {
if len(data) == 0 {
return 0, nil
}
g.start()
n, e = io.WriteString(g.writer, data)
g.size += n
return
}