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() }) }