Enabling brotli compression in Go and Chi

September 07, 2021

2 min read

Why Brotli?

Brotli is supported on most modern browsers. For browsers that don't support Brotli, the compression method will fall back to gzip or deflate based on the request's Accept-Encoding header. Enabling Brotli compression is an easy performance win.

Brotli is usually more effective at compressing compared to gzip and deflate. When I enabled Brotli compression for Highlight, I saw response sizes decrease around 40% with no latency increases (for the most part requests were faster!).

The Code Changes

Installing Dependencies

# Install the Chi, older versions of Chi don't support Brotli
go get -u

# Install the package that will do the Brotli compression
go get -u

Enabling Brotli Compression

r := chi.NewMux()
// /* means to compress all content types that can be compressed.
compressor := middleware.NewCompressor(5, "/*")
compressor.SetEncoder("br", func(w io.Writer, level int) io.Writer {
	params := brotli_enc.NewBrotliParams()
	return brotli_enc.NewBrotliWriter(params, w)

The "/*" means to compress all content types that can be compressed. These are the supported types:

var defaultCompressibleContentTypes = []string{

That's it, congrats on the easy performance win for you and your users!