Compress Middleware¶
Gzip compression for responses.
Usage¶
Default Configuration¶
Custom Configuration¶
app.Use(middleware.Compress(middleware.CompressConfig{
Level: gzip.BestSpeed,
MinSize: 1024,
ContentTypes: []string{
"text/plain",
"text/html",
"application/json",
},
}))
Configuration Options¶
| Option | Type | Default | Description |
|---|---|---|---|
Level | int | gzip.DefaultCompression | Compression level |
MinSize | int | 1024 | Minimum size to compress |
ContentTypes | []string | See below | Content types to compress |
Default Content Types¶
text/plaintext/htmltext/csstext/javascriptapplication/jsonapplication/javascriptapplication/xml
Compression Levels¶
| Level | Constant | Description |
|---|---|---|
| -1 | gzip.DefaultCompression | Balance of speed and size |
| 0 | gzip.NoCompression | No compression |
| 1 | gzip.BestSpeed | Fastest compression |
| 9 | gzip.BestCompression | Smallest size |
Examples¶
Fast Compression¶
Best Compression¶
Custom Content Types¶
app.Use(middleware.Compress(middleware.CompressConfig{
ContentTypes: []string{
"application/json",
"text/html",
"text/css",
"application/javascript",
},
}))
Higher Threshold¶
// Only compress responses > 2KB
app.Use(middleware.Compress(middleware.CompressConfig{
MinSize: 2048,
}))
How It Works¶
- Checks if client accepts gzip (
Accept-Encoding: gzip) - Checks if response content type is compressible
- Buffers response until
MinSizeis reached - If large enough, compresses with gzip
- Sets
Content-Encoding: gzipheader
Response Headers¶
When compression is applied:
The Content-Length header is removed since the compressed size differs.
Best Practices¶
- Don't compress already compressed content - Images, videos, etc.
- Set appropriate MinSize - Small responses don't benefit from compression
- Consider CPU usage - Compression uses CPU
- Use BestSpeed for high-traffic - Lower CPU usage