Skip to content

Instantly share code, notes, and snippets.

Forked from bryfry/gzip.go
Created Jul 3, 2019
What would you like to do?
Idiomatic golang net/http gzip transparent compression (works with Alice)
package main
import (
// Gzip Compression
type gzipResponseWriter struct {
func (w gzipResponseWriter) Write(b []byte) (int, error) {
return w.Writer.Write(b)
func Gzip(handler http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
handler.ServeHTTP(w, r)
w.Header().Set("Content-Encoding", "gzip")
gz := gzip.NewWriter(w)
defer gz.Close()
gzw := gzipResponseWriter{Writer: gz, ResponseWriter: w}
handler.ServeHTTP(gzw, r)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment