Created
May 27, 2014 09:24
-
-
Save hjr265/885d08e9c7ecd5ee91f9 to your computer and use it in GitHub Desktop.
Compress Handler
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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