TalkingJson
TalkingJson

Reputation: 101

Go add gzip compression to all handlers

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

Upvotes: 3

Views: 3663

Answers (1)

Thundercat
Thundercat

Reputation: 120941

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

Upvotes: 6

Related Questions