我想向所有处理程序添加gzip压缩。现在看起来如何
func gzipHandler(fn http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
fn(w, r)
return
}
w.Header().Set("Content-Encoding", "gzip")
gz := gzip.NewWriter(w)
defer gz.Close()
fn(gzipResponseWriter{Writer: gz, ResponseWriter: w}, r)
}
}
http.Handle("/", http.FileServer(http.Dir("./index")))
http.HandleFunc("/json", gzipHandler(sendJSONHandler))
http.HandleFunc("/contact", gzipHandler(contactHandler))
http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("./static"))))
http.ListenAndServe(":80", cacheHandler(http.DefaultServeMux))
我想做与cacheHandler
答案 0 :(得分:2)
更改gzip中间件以使用http.Handler而不是http.HandlerFunc:
func gzipHandler(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
h.ServeHTTP(w, r)
return
}
w.Header().Set("Content-Encoding", "gzip")
gz := gzip.NewWriter(w)
defer gz.Close()
h.ServeHTTP(gzipResponseWriter{Writer: gz, ResponseWriter: w}, r)
})
}
包装根处理程序:
http.ListenAndServe(":80", gzipHandler(cacheHandler(http.DefaultServeMux)))
如果cacheHandler is also middleware that you are writing,那么您可能想要组合中间件:
func wrap(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Cache-Control", "max-age=1800") // <--- add code from cache handler
if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
h.ServeHTTP(w, r)
return
}
w.Header().Set("Content-Encoding", "gzip")
gz := gzip.NewWriter(w)
defer gz.Close()
h.ServeHTTP(gzipResponseWriter{Writer: gz, ResponseWriter: w}, r)
})
}
...
http.ListenAndServe(":80", wrap(http.DefaultServeMux))