Skip to content

Instantly share code, notes, and snippets.

@jasonmoo
Created July 28, 2014 00:02
Show Gist options
  • Save jasonmoo/849eb5af71076790f906 to your computer and use it in GitHub Desktop.
Save jasonmoo/849eb5af71076790f906 to your computer and use it in GitHub Desktop.
A simple wrapper for http gzipped response
type (
GzipResponseWriter struct {
io.Writer
http.ResponseWriter
}
)
func (g GzipResponseWriter) Write(b []byte) (int, error) {
return g.Writer.Write(b)
}
func NewGzipHandler(f func(w http.ResponseWriter, req *http.Request)) http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
encoding := req.Header.Get("Accept-Encoding")
if strings.Contains(encoding, "gzip") {
w.Header().Set("Content-Encoding", "gzip")
gz := gzip.NewWriter(w)
defer gz.Close()
f(GzipResponseWriter{gz, w}, req)
} else {
f(w, req)
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment