forked from OneOfOne/gserv
-
Notifications
You must be signed in to change notification settings - Fork 0
/
compression.go
72 lines (60 loc) · 1.19 KB
/
compression.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
package gserv
import (
"compress/gzip"
"io"
"net/http"
"sync"
)
const (
acceptHeader = "Accept-Encoding"
contentTypeHeader = "Content-Type"
encodingHeader = "Content-Encoding"
lenHeader = "Content-Length"
brEnc = "br"
gzEnc = "gzip"
)
var gzPool = sync.Pool{
New: func() any {
w := gzip.NewWriter(io.Discard)
return &gzipRW{nil, w, false}
},
}
func getGzipRW(rw http.ResponseWriter) *gzipRW {
rw.Header().Set(encodingHeader, gzEnc)
grw := gzPool.Get().(*gzipRW)
grw.ResponseWriter, grw.wrote = rw, false
grw.gz.Reset(rw)
return grw
}
type gzipRW struct {
http.ResponseWriter
gz *gzip.Writer
wrote bool
}
func (w *gzipRW) ensureHeaders(status int) {
if w.wrote {
return
}
w.wrote = true
h := w.Header()
h.Del(lenHeader)
h.Del(acceptHeader)
h.Set(encodingHeader, gzEnc)
w.ResponseWriter.WriteHeader(status)
}
func (w *gzipRW) WriteHeader(status int) {
w.ensureHeaders(status)
}
func (w *gzipRW) Flush() {
w.ensureHeaders(http.StatusOK)
w.gz.Flush()
w.ResponseWriter.(http.Flusher).Flush()
}
func (w *gzipRW) Write(b []byte) (int, error) {
w.ensureHeaders(http.StatusOK)
return w.gz.Write(b)
}
func (w *gzipRW) Reset() {
w.gz.Close()
gzPool.Put(w)
}