-
Notifications
You must be signed in to change notification settings - Fork 2
/
compress.go
65 lines (56 loc) · 1.22 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
package mware
import (
"compress/gzip"
"io"
"net/http"
"strings"
"sync"
)
var pool = sync.Pool{
New: func() interface{} {
return gzip.NewWriter(io.Discard)
},
}
type gzipWriter struct {
http.ResponseWriter
writer *gzip.Writer
headersDone bool
}
func GZip(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
w.Header().Set("Content-Encoding", "gzip")
w.Header().Set("Vary", "Accept-Encoding")
writer := pool.Get().(*gzip.Writer)
writer.Reset(w)
gz := &gzipWriter{writer: writer, ResponseWriter: w}
defer func() {
_ = gz.Close()
}()
next(gz, r)
} else {
next(w, r)
}
}
}
func (w *gzipWriter) WriteHeader(code int) {
w.ResponseWriter.Header().Del("Content-Length")
w.ResponseWriter.WriteHeader(code)
w.headersDone = true
}
func (w *gzipWriter) Write(b []byte) (int, error) {
if !w.headersDone {
w.WriteHeader(http.StatusOK)
}
return w.writer.Write(b)
}
func (w *gzipWriter) Flush() {
_ = w.writer.Flush()
if flusher, ok := w.ResponseWriter.(http.Flusher); ok {
flusher.Flush()
}
}
func (w *gzipWriter) Close() error {
defer pool.Put(w.writer)
return w.writer.Close()
}