Skip to content

Instantly share code, notes, and snippets.

@hjr265
Created May 27, 2014 09:24
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 hjr265/885d08e9c7ecd5ee91f9 to your computer and use it in GitHub Desktop.
Save hjr265/885d08e9c7ecd5ee91f9 to your computer and use it in GitHub Desktop.
Compress Handler
package main
import (
"compress/gzip"
"io"
"net/http"
"strings"
)
type GzipResponseWriter struct {
*gzip.Writer
http.ResponseWriter
}
func NewGzipResponseWriter(w http.ResponseWriter) http.ResponseWriter {
return &GzipResponseWriter{
Writer: gzip.NewWriter(w),
ResponseWriter: w,
}
}
func (w *GzipResponseWriter) Header() http.Header {
return w.ResponseWriter.Header()
}
func (w *GzipResponseWriter) Write(b []byte) (int, error) {
h := w.ResponseWriter.Header()
if h.Get("Content-Type") == "" {
h.Set("Content-Type", http.DetectContentType(b))
}
return w.Writer.Write(b)
}
func CompressHandler(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
L:
for _, enc := range strings.Split(r.Header.Get("Accept-Encoding"), ",") {
switch enc {
case "gzip":
w.Header().Set("Content-Encoding", "gzip")
w.Header().Add("Vary", "Accept-Encoding")
cw := NewGzipResponseWriter(w)
switch x := cw.(type) {
case io.Closer:
defer x.Close()
}
w = cw
break L
}
}
h.ServeHTTP(w, r)
})
}
func main() {
http.Handle("/", CompressHandler(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
for i := 0; i < 32; i++ {
io.WriteString(w, "Hello, gzip!\n")
}
})))
http.ListenAndServe(":8080", nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment