How to Implement Compression Middleware (gzip) in Go

Web
Implement gzip compression in Go by wrapping your handler with a middleware that checks Accept-Encoding and writes to a gzip.Writer.

Wrap your HTTP handler with http.HandlerFunc that checks for gzip in the Accept-Encoding header and writes to a gzip.Writer if supported.

import (
	"compress/gzip"
	"net/http"
)

func GzipMiddleware(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if !strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
			next.ServeHTTP(w, r)
			return
		}
		w.Header().Set("Content-Encoding", "gzip")
		gz := gzip.NewWriter(w)
		defer gz.Close()
		next.ServeHTTP(gz, r)
	})
}

Apply it to your router: mux.Use(GzipMiddleware) or wrap your http.ListenAndServe handler.