forked from nytimes/gziphandler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gzip.go
47 lines (42 loc) · 980 Bytes
/
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
package gziphandler
import (
"compress/gzip"
"io"
"net/http"
"strings"
)
type gzipResponseWriter struct {
io.Writer
http.ResponseWriter
}
// Optional Pool
// var (
// pool = sync.Pool{
// New: func() interface{} {
// w,_ := gzip.NewWriterLevel(nil,1)
// return &gzipResponseWriter{
// w:w,
// }
// }
// }
// )
func (w gzipResponseWriter) Write(b []byte) (int, error) {
if w.Header().Get("Content-Type") == "" {
w.Header().Set("Content-Type", http.DetectContentType(b))
}
return w.Writer.Write(b)
}
// Gzipler is the middleware
func Gzipler(h http.Handler, level int) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
h.ServeHTTP(w, r)
return
}
w.Header().Set("Content-Encoding", "gzip")
gz, _ := gzip.NewWriterLevel(w, level)
defer gz.Close()
gw := gzipResponseWriter{Writer: gz, ResponseWriter: w}
h.ServeHTTP(gw, r)
})
}