Package compress provides a clever gzip compressing handler.
It takes care to not handle small contents, or contents that are already compressed (like JPEG, MPEG or PDF).
Trying to gzip them not only wastes CPU but can potentially increase the response size.
-
Get package:
go get -u github.com/gowww/compress
-
Import it in your code:
import "github.com/gowww/compress"
To wrap an http.Handler, use Handle:
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "Hello")
})
http.ListenAndServe(":8080", compress.Handle(handler))
To wrap an http.HandlerFunc, use HandleFunc:
http.Handle("/", compress.HandleFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "Hello")
}))
http.ListenAndServe(":8080", nil)
All in all, make sure to include this handler above any other handler that may write the response.