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
| Option | Type | Default | Description |
|---|---|---|---|
Level | int | 6 | Compression level (1-9) |
MinSize | int | 1024 | Minimum response size to compress |
ContentTypes | []string | Text types | Content types to compress |
Examples
Gzip Compression
Custom Compression Level
With Options
Auto-Select Encoding
API Reference
Functions
Compression Levels
| Level | Description |
|---|---|
| 1 | Best speed, least compression |
| 6 | Default balance |
| 9 | Best compression, slowest |
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
Testing
The compress middleware includes comprehensive test coverage for various scenarios:| Test Case | Description | Expected Behavior |
|---|---|---|
TestGzip/compresses response | Tests basic gzip compression with large response | Response is compressed with gzip, Content-Encoding header set to “gzip”, body can be decompressed correctly |
TestGzip/skips without accept-encoding | Tests behavior when Accept-Encoding header is missing | Response is not compressed, no Content-Encoding header set |
TestGzip/sets vary header | Tests Vary header is properly set | Vary header contains “Accept-Encoding” |
TestGzipLevel | Tests gzip compression with specific level (level 9) | Response is compressed with specified compression level, Content-Encoding set to “gzip” |
TestDeflate | Tests deflate compression algorithm | Response is compressed with deflate, Content-Encoding header set to “deflate” |
TestNew_SmallResponse | Tests MinSize threshold with response smaller than limit | Small responses (< MinSize) are not compressed |
TestNew_NonCompressibleType | Tests content type filtering | Non-text content types (e.g., application/octet-stream) are not compressed |
TestNew_AlreadyEncoded | Tests handling of pre-encoded responses | Existing Content-Encoding header is preserved, no double compression |
TestNew_AutoSelectEncoding | Tests automatic encoding selection based on Accept-Encoding | Middleware selects gzip or deflate based on client preference, prefers gzip when both available |