-
Notifications
You must be signed in to change notification settings - Fork 1
/
gzip.go
44 lines (35 loc) · 863 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
package gzip
import (
"compress/gzip"
"net/http"
"strings"
)
type gzipResponseWriter struct {
*gzip.Writer
http.ResponseWriter
}
func (w *gzipResponseWriter) Header() http.Header {
return w.ResponseWriter.Header()
}
func (w *gzipResponseWriter) Write(b []byte) (int, error) {
h := w.ResponseWriter.Header()
if h.Get("Content-Type") == "" {
h.Set("Content-Type", http.DetectContentType(b))
}
return w.Writer.Write(b)
}
func GzipHandler(h http.Handler) http.Handler {
fn := 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")
w.Header().Set("Vary", "Accept-Encoding")
gw := gzip.NewWriter(w)
defer gw.Close()
w = &gzipResponseWriter{gw, w}
h.ServeHTTP(w, r)
}
return http.HandlerFunc(fn)
}