Skip to content

Instantly share code, notes, and snippets.

@dvasilen
Forked from bryfry/gzip.go
Created July 3, 2019 19:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dvasilen/a8a5e66453adb4cd7495cec140d118ca to your computer and use it in GitHub Desktop.
Save dvasilen/a8a5e66453adb4cd7495cec140d118ca to your computer and use it in GitHub Desktop.
Idiomatic golang net/http gzip transparent compression (works with Alice)
package main
import (
"compress/gzip"
"io"
"net/http"
"strings"
)
// Gzip Compression
type gzipResponseWriter struct {
io.Writer
http.ResponseWriter
}
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)
return
}
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