Skip to content

Instantly share code, notes, and snippets.

@daneharrigan
Last active August 29, 2015 14:18
Show Gist options
  • Save daneharrigan/341ce7ed7e0bde321eaf to your computer and use it in GitHub Desktop.
Save daneharrigan/341ce7ed7e0bde321eaf to your computer and use it in GitHub Desktop.
package main
import (
"compress/gzip"
"encoding/json"
"io"
"net/http"
)
type GzipHandler struct {
http.Handler
}
func (g *GzipHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Accept-Encoding") == "gzip" {
gw := gzip.NewWriter(w)
defer gw.Close()
w = CompressedWriter{w, gw}
w.Header().Set("Content-Encoding", "gzip")
w.Header().Set("Vary", "Accept-Encoding")
}
g.Handler.ServeHTTP(w, r)
}
type CompressedWriter struct {
http.ResponseWriter
w io.Writer
}
func (c CompressedWriter) Write(b []byte) (int, error) {
return c.w.Write(b)
}
type Example struct {
Message string
}
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
example := Example{Message: "compression example"}
json.NewEncoder(w).Encode(example)
})
http.ListenAndServe(":5000", &GzipHandler{http.DefaultServeMux})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment