Gzip Response Compression Middleware

Compress HTTP responses when the client advertises gzip support, set Vary correctly, and skip negotiation for other clients.

GoData Fetching

Code

gosnippet
41 lines
package main

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

type gzipWriter struct {
	http.ResponseWriter
	writer *gzip.Writer
}

func (g *gzipWriter) Write(data []byte) (int, error) {
	return g.writer.Write(data)
}

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

func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "text/plain; charset=utf-8")
		fmt.Fprintln(w, strings.Repeat("hello gzip ", 64))
	})
	_ = http.ListenAndServe(":8080", GzipMiddleware(mux))
}

Step order in the source

The working surface is the functions Write, GzipMiddleware and main — everything else is wiring.

defer inverts the usual order — register now, run at return — which is why cleanup cannot be skipped.

Putting it to use

The primary signature is func (g *gzipWriter) Write(data []byte) (int, error)

main sequences GzipMiddleware; executing the file runs that flow once.

Core lines

func (g *gzipWriter) Write(data []byte) (int, error) {
	return g.writer.Write(data)
}
func main() {
	mux := http.NewServeMux()
	mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "text/plain; charset=utf-8")
		fmt.Fprintln(w, strings.Repeat("hello gzip ", 64))
	})
	_ = http.ListenAndServe(":8080", GzipMiddleware(mux))
}
defer compressor.Close()

Interactive Tools for This Topic

FAQ

How do you run Gzip Response Compression Middleware?
Run the file on its own; every call resolves against the standard surface it already imports.