Last active
August 29, 2015 14:18
-
-
Save daneharrigan/341ce7ed7e0bde321eaf to your computer and use it in GitHub Desktop.
This file contains hidden or 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" | |
"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