blob: ab21180b9e51d607dc1b11560c4c4cc47a034a39 (
plain)
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
|
package gziphandler
import (
"compress/gzip"
"net/http"
"strings"
)
type gw struct {
http.ResponseWriter
w *gzip.Writer
}
func (w *gw) Write(d []byte) (int, error) {
return w.w.Write(d)
}
func (w *gw) Close() error {
return w.w.Close()
}
func acceptsGzip(r *http.Request) bool {
ae := r.Header.Get("Accept-Encoding")
for _, e := range strings.Split(ae, ",") {
vals := strings.Split(e, ";")
if len(vals) < 1 {
continue
}
if strings.TrimSpace(vals[0]) == "gzip" {
return true
}
}
return false
}
// Handler returns an http.Handler that compresses the response data written
// by an existing handler h, using the compress/gzip.Writer with default
// compression level.
func Handler(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !acceptsGzip(r) {
h.ServeHTTP(w, r)
return
}
w.Header().Set("Content-Encoding", "gzip")
gw := &gw{
ResponseWriter: w,
w: gzip.NewWriter(w),
}
h.ServeHTTP(gw, r)
gw.Close()
})
}
|