Skip to content

Instantly share code, notes, and snippets.

@rizalgowandy
Forked from CJEnright/gzip.go
Created June 29, 2019 07:00
Show Gist options
  • Save rizalgowandy/9bfc070d2c78b32116e186515c71c5f8 to your computer and use it in GitHub Desktop.
Save rizalgowandy/9bfc070d2c78b32116e186515c71c5f8 to your computer and use it in GitHub Desktop.
Idiomatic golang net/http gzip transparent compression, an updated version of https://gist.github.com/bryfry/09a650eb8aac0fb76c24
package main
import (
"net/http"
"compress/gzip"
"io/ioutil"
"strings"
"sync"
"io"
)
var gzPool = sync.Pool {
New: func() interface{} {
w := gzip.NewWriter(ioutil.Discard)
return w
},
}
type gzipResponseWriter struct {
io.Writer
http.ResponseWriter
}
func (w *gzipResponseWriter) WriteHeader(status int) {
w.Header().Del("Content-Length")
w.ResponseWriter.WriteHeader(status)
}
func (w *gzipResponseWriter) Write(b []byte) (int, error) {
return w.Writer.Write(b)
}
func Gzip(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 := gzPool.Get().(*gzip.Writer)
defer gzPool.Put(gz)
gz.Reset(w)
defer gz.Close()
next.ServeHTTP(&gzipResponseWriter{ResponseWriter: w, Writer: gz}, r)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment