Skip to content

Instantly share code, notes, and snippets.

@karrick
Last active January 10, 2017 20:34
Show Gist options
  • Save karrick/6c5960603b49c6f06e543da8f8ddaf84 to your computer and use it in GitHub Desktop.
Save karrick/6c5960603b49c6f06e543da8f8ddaf84 to your computer and use it in GitHub Desktop.
// GzipHandler returns a new http.Handler that optionally compresses the response text using the
// gzip compression algorithm when the HTTP request's Accept-Encoding header includes the string
// "gzip".
func GzipHandler(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
next.ServeHTTP(w, r)
return
}
w.Header().Set("Content-Encoding", "gzip")
gz := gzip.NewWriter(w)
defer func() { _ = gz.Close() }()
next.ServeHTTP(gzipResponseWriter{ResponseWriter: w, gzipWriter: gz}, r)
})
}
type gzipResponseWriter struct {
http.ResponseWriter
gzipWriter io.Writer
}
func (g gzipResponseWriter) Write(b []byte) (int, error) {
return g.gzipWriter.Write(b)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment