-
Notifications
You must be signed in to change notification settings - Fork 0
/
gzip.go
65 lines (52 loc) · 1.38 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
package api
import (
"compress/gzip"
"net/http"
"strings"
"github.com/DeviaVir/instio/pkg/system/db"
)
// Gzip wraps a HandlerFunc to compress responses when possible.
func Gzip(next http.HandlerFunc) http.HandlerFunc {
return http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
if db.ConfigCache("gzip_disabled").(bool) == true {
next.ServeHTTP(res, req)
return
}
// Check if req header content-encoding supports gzip.
if strings.Contains(req.Header.Get("Accept-Encoding"), "gzip") {
// Gzip response data.
res.Header().Set("Content-Encoding", "gzip")
gzWriter := gzip.NewWriter(res)
defer gzWriter.Close()
var gzres gzipResponseWriter
if pusher, ok := res.(http.Pusher); ok {
gzres = gzipResponseWriter{res, pusher, gzWriter}
} else {
gzres = gzipResponseWriter{res, nil, gzWriter}
}
next.ServeHTTP(gzres, req)
return
}
next.ServeHTTP(res, req)
})
}
type gzipResponseWriter struct {
http.ResponseWriter
pusher http.Pusher
gw *gzip.Writer
}
func (gzw gzipResponseWriter) Write(p []byte) (int, error) {
return gzw.gw.Write(p)
}
func (gzw gzipResponseWriter) Push(target string, opts *http.PushOptions) error {
if gzw.pusher == nil {
return nil
}
if opts == nil {
opts = &http.PushOptions{
Header: make(http.Header),
}
}
opts.Header.Set("Accept-Encoding", "gzip")
return gzw.pusher.Push(target, opts)
}