forked from pinguo/pgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGzip.go
107 lines (87 loc) · 1.82 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
package pgo
import (
"compress/gzip"
"io"
"io/ioutil"
"net/http"
"path/filepath"
"strings"
"sync"
)
// Gzip gzip compression plugin
type Gzip struct {
pool sync.Pool
}
func (g *Gzip) Construct() {
g.pool.New = func() interface{} {
return &gzipWriter{writer: gzip.NewWriter(ioutil.Discard)}
}
}
func (g *Gzip) HandleRequest(ctx *Context) {
ae := ctx.GetHeader("Accept-Encoding", "")
if !strings.Contains(ae, "gzip") {
return
}
ext := filepath.Ext(ctx.GetPath())
switch strings.ToLower(ext) {
case ".png", ".gif", ".jpeg", ".jpg", ".ico":
return
}
gw := g.pool.Get().(*gzipWriter)
gw.reset(ctx)
defer func() {
gw.finish()
g.pool.Put(gw)
}()
ctx.Next()
}
type gzipWriter struct {
http.ResponseWriter
writer *gzip.Writer
ctx *Context
size int
}
func (g *gzipWriter) reset(ctx *Context) {
g.ResponseWriter = ctx.GetOutput()
g.ctx = ctx
g.size = -1
ctx.SetOutput(g)
}
func (g *gzipWriter) finish() {
if g.size > 0 {
g.writer.Close()
}
}
func (g *gzipWriter) start() {
if g.size == -1 {
g.size = 0
g.writer.Reset(g.ResponseWriter)
g.ctx.SetHeader("Content-Encoding", "gzip")
}
}
func (g *gzipWriter) Flush() {
if g.size > 0 {
g.writer.Flush()
}
if flusher, ok := g.ResponseWriter.(http.Flusher); ok {
flusher.Flush()
}
}
func (g *gzipWriter) 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 *gzipWriter) 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
}