Last active
January 10, 2017 20:34
-
-
Save karrick/6c5960603b49c6f06e543da8f8ddaf84 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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