DEV Community

John Pham
John Pham

Posted on • Originally published at pham.codes

4 1

Enabling brotli compression in Go and Chi

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 github.com/go-chi/chi

# Install the package that will do the Brotli compression
go get -u gopkg.in/kothar/brotli-go.v0
Enter fullscreen mode Exit fullscreen mode

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()
    params.SetQuality(level)
    return brotli_enc.NewBrotliWriter(params, w)
})
r.Use(compressor.Handler)
Enter fullscreen mode Exit fullscreen mode

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

var defaultCompressibleContentTypes = []string{
    "text/html",
    "text/css",
    "text/plain",
    "text/javascript",
    "application/javascript",
    "application/x-javascript",
    "application/json",
    "application/atom+xml",
    "application/rss+xml",
    "image/svg+xml",
}
Enter fullscreen mode Exit fullscreen mode

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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

The best way to debug slow web pages cover image

The best way to debug slow web pages

Tools like Page Speed Insights and Google Lighthouse are great for providing advice for front end performance issues. But what these tools can’t do, is evaluate performance across your entire stack of distributed services and applications.

Watch video