Skip to content

Instantly share code, notes, and snippets.

@yanmhlv
Forked from the42/gist:1956518
Created September 15, 2017 12:07
Show Gist options
  • Save yanmhlv/a608d7a342cd00b839147d15dbbf9dcd to your computer and use it in GitHub Desktop.
Save yanmhlv/a608d7a342cd00b839147d15dbbf9dcd to your computer and use it in GitHub Desktop.
GZip encoding for GO V1 using custom responsewriter
package main
import (
"compress/gzip"
"io"
"net/http"
"strings"
)
type gzipResponseWriter struct {
io.Writer
http.ResponseWriter
}
func (w gzipResponseWriter) Write(b []byte) (int, error) {
return w.Writer.Write(b)
}
func makeGzipHandler(fn http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
fn(w, r)
return
}
w.Header().Set("Content-Encoding", "gzip")
gz := gzip.NewWriter(w)
defer gz.Close()
gzr := gzipResponseWriter{Writer: gz, ResponseWriter: w}
fn(gzr, r)
}
}
func handler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/plain")
w.Write([]byte("This is a test."))
}
func main() {
http.ListenAndServe(":1113", makeGzipHandler(handler))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment