du22399 2018-06-17 15:58
浏览 26
已采纳

将gzip压缩添加到所有处理程序

I'm want to add gzip compression to all handlers. Here how it looks now

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

I want to do something like in last line with cacheHandler

  • 写回答

1条回答 默认 最新

  • doubi3929 2018-06-17 16:02
    关注

    Change the gzip middleware to work with http.Handler instead of 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)
        })
    }
    

    Wrap the root handler:

    http.ListenAndServe(":80", gzipHandler(cacheHandler(http.DefaultServeMux)))
    

    If cacheHandler is also middleware that you are writing, then you might want to combine the middleware:

    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))
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料