-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathhttpgzip.go
42 lines (38 loc) · 1.04 KB
/
httpgzip.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
// Package httpgzip provides a http handler wrapper to transparently
// add gzip compression. It will sniff the content type based on the
// uncompressed data if necessary.
package httpgzip
import (
"compress/gzip"
"io"
"net/http"
"strings"
)
type gzipResponseWriter struct {
io.Writer
http.ResponseWriter
sniffDone bool
}
func (w *gzipResponseWriter) Write(b []byte) (int, error) {
if !w.sniffDone {
if w.Header().Get("Content-Type") == "" {
w.Header().Set("Content-Type", http.DetectContentType(b))
}
w.sniffDone = true
}
return w.Writer.Write(b)
}
// Wrap a http.Handler to support transparent gzip encoding.
func NewHandler(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Vary", "Accept-Encoding")
if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
h.ServeHTTP(w, r)
return
}
w.Header().Set("Content-Encoding", "gzip")
gz := gzip.NewWriter(w)
defer gz.Close()
h.ServeHTTP(&gzipResponseWriter{Writer: gz, ResponseWriter: w}, r)
})
}