/
compress.go
94 lines (83 loc) · 1.64 KB
/
compress.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
package mux
import (
"bytes"
"net/http"
"sync"
)
var bufPool *sync.Pool
var compressorPool *sync.Pool
func init() {
bufPool = &sync.Pool{
New: func() interface{} {
return bytes.NewBuffer(nil)
},
}
compressorPool = &sync.Pool{
New: func() interface{} {
return &Compressor{}
},
}
}
// putBuffer set Buffer stream
func putBuffer(buf *bytes.Buffer) {
buf.Reset()
bufPool.Put(buf)
}
// putCompressor set Compressor stream
func putCompressor(compressor *Compressor) {
if compressor.buf != nil {
putBuffer(compressor.buf)
}
compressorPool.Put(compressor)
}
type CompressWriter interface {
Write(p []byte) (int, error)
Flush() error
Close() error
}
type Compressor struct {
writer CompressWriter
w http.ResponseWriter
compress bool
compressType string
buf *bytes.Buffer
useBuffer bool
}
func newCompressor(useBuffer bool) *Compressor {
c := compressorPool.Get().(*Compressor)
c.useBuffer = useBuffer
if useBuffer {
buf := bufPool.Get().(*bytes.Buffer)
c.buf = buf
}
return c
}
func (c *Compressor) ready(w http.ResponseWriter, r *http.Request) {
if !CheckAcceptEncoding(r, c.compressType) {
c.compress = false
return
}
SetContentEncoding(w, c.compressType)
c.compress = true
}
// Write byte
func (c *Compressor) Write(b []byte) (int, error) {
if c.compress {
SetHeader(c.w, ContentType, http.DetectContentType(b))
return c.writer.Write(b)
} else {
return c.w.Write(b)
}
}
// Close a Compressor
func (c *Compressor) Close() error {
defer putCompressor(c)
if c.compress {
c.writer.Flush()
if c.useBuffer {
c.w.Write(c.buf.Bytes())
}
return c.writer.Close()
}
return nil
}