【问题标题】:Go add gzip compression to all handlers向所有处理程序添加 gzip 压缩
【发布时间】:2018-06-17 15:58:22
【问题描述】:

我想为所有处理程序添加 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 做类似的事情

【问题讨论】:

    标签: go


    【解决方案1】:

    更改 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))
    

    【讨论】:

    • 谢谢,这就是我想要的!
    猜你喜欢
    • 2011-06-02
    • 1970-01-01
    • 2011-05-21
    • 2012-08-14
    • 2010-12-17
    • 1970-01-01
    • 1970-01-01
    • 2015-07-14
    • 2011-04-20
    相关资源
    最近更新 更多