Overview
Thecompress middleware automatically compresses HTTP responses using gzip or deflate encoding when the client supports it. This reduces bandwidth usage and improves load times for text-based content.
Use it when you need:
- Reduced bandwidth for API responses
- Faster page loads for web applications
- Compression for JSON, HTML, CSS, and JavaScript
Installation
Quick Start
Configuration
Options
Examples
Gzip Compression
Custom Compression Level
With Options
Auto-Select Encoding
API Reference
Functions
Compression Levels
Behavior
- Automatically sets
Content-Encodingheader - Adds
Vary: Accept-Encodingheader - Skips compression if client doesn’t support it
- Skips already-encoded responses
- Skips responses smaller than
MinSize
Technical Details
Implementation Overview
The compress middleware uses a buffering strategy to determine whether compression should be applied:- Buffering Phase: Responses are buffered until they reach the
MinSizethreshold - Decision Point: Once the threshold is reached, the middleware checks:
- If the client supports the requested encoding (via
Accept-Encodingheader) - If the content type is compressible (matches
ContentTypeslist) - If the response is not already encoded (no existing
Content-Encodingheader)
- If the client supports the requested encoding (via
- Compression Phase: If all checks pass, the appropriate compression writer is applied
Writer Pooling
The middleware usessync.Pool to efficiently reuse compression writers:
- Gzip Pool: Maintains a pool of
gzip.Writerinstances - Deflate Pool: Maintains a pool of
flate.Writerinstances - Writers are reset and returned to the pool after each request
- This reduces garbage collection pressure and improves performance
Custom Response Writer
ThecompressWriter wraps the standard http.ResponseWriter and provides:
- Buffering: Accumulates response data until compression decision is made
- Lazy Header Writing: Delays header writing until compression status is determined
- Automatic Cleanup: Ensures compression writers are properly closed and returned to pool
- Flush Support: Implements
http.Flusherfor streaming responses
Encoding Selection
When usingNew() with auto-selection:
- Checks for
gzipinAccept-Encodingheader first (preferred) - Falls back to
deflateif gzip is not supported - Uses no compression if neither is supported
Gzip(), Deflate()):
- Only applies compression if the client explicitly supports the selected encoding
Default Content Types
The following content types are compressed by default:text/html,text/css,text/plain,text/javascript,text/xmlapplication/json,application/javascript,application/xmlapplication/xhtml+xml,application/rss+xml,application/atom+xmlimage/svg+xml
Best Practices
- Use level 6 for most applications (good balance)
- Set appropriate
MinSizeto avoid compressing tiny responses - Only compress text-based content types
- Place before other response-modifying middleware