Skip to content

Compression ​

Added: v1.0.0

Gzip response compression middleware. Compresses responses when the client includes Accept-Encoding: gzip in the request.

Usage ​

go
r.Use(middleware.Compress())

Custom Compression Level ​

go
r.Use(middleware.CompressWithLevel(gzip.BestSpeed))

CompressWithLevel accepts an integer compression level (1 = BestSpeed, 9 = BestCompression).

How It Works ​

  • Checks all Accept-Encoding header values for gzip, honoring q-values (gzip;q=0 disables compression), the * wildcard, and case-insensitive tokens
  • Buffers responses below 1 KB and serves them uncompressed to save CPU; larger payloads switch to streaming gzip
  • Wraps the response writer with a gzip.Writer
  • Sets Content-Encoding: gzip and Vary: Accept-Encoding headers
  • Skips compression when a response already carries a Content-Encoding header

Released under the MIT License.