| 1 |
Gzip/Zstd HTTP Middleware |
| 2 |
==================== |
| 3 |
|
| 4 |
This Go package wraps HTTP *server* handlers to transparently compress the |
| 5 |
response body using gzip or zstd, for clients which support it. |
| 6 |
|
| 7 |
Both gzip and zstd compression are enabled by default. When a client supports both, |
| 8 |
zstd is preferred due to its better compression ratio and speed. |
| 9 |
|
| 10 |
For HTTP *clients* we provide a transport wrapper that will do gzip/zstd decompression |
| 11 |
faster than what the standard library offers. |
| 12 |
|
| 13 |
Both the client and server wrappers are fully compatible with other servers and clients. |
| 14 |
|
| 15 |
This package is forked from the dead [nytimes/gziphandler](https://github.com/nytimes/gziphandler) |
| 16 |
and extends functionality for it. |
| 17 |
|
| 18 |
## Install |
| 19 |
```bash |
| 20 |
go get -u github.com/klauspost/compress |
| 21 |
``` |
| 22 |
|
| 23 |
## Documentation |
| 24 |
|
| 25 |
[](https://pkg.go.dev/github.com/klauspost/compress/gzhttp) |
| 26 |
|
| 27 |
|
| 28 |
## Usage |
| 29 |
|
| 30 |
There are 2 main parts, one for http servers and one for http clients. |
| 31 |
|
| 32 |
### Client |
| 33 |
|
| 34 |
The standard library automatically adds gzip compression to most requests |
| 35 |
and handles decompression of the responses. |
| 36 |
|
| 37 |
However, by wrapping the transport we are able to override this and provide |
| 38 |
our own (faster) decompressor. |
| 39 |
|
| 40 |
Wrapping is done on the Transport of the http client: |
| 41 |
|
| 42 |
```Go |
| 43 |
func ExampleTransport() { |
| 44 |
// Get an HTTP client. |
| 45 |
client := http.Client{ |
| 46 |
// Wrap the transport: |
| 47 |
Transport: gzhttp.Transport(http.DefaultTransport), |
| 48 |
} |
| 49 |
|
| 50 |
resp, err := client.Get("https://google.com") |
| 51 |
if err != nil { |
| 52 |
return |
| 53 |
} |
| 54 |
defer resp.Body.Close() |
| 55 |
|
| 56 |
body, _ := ioutil.ReadAll(resp.Body) |
| 57 |
fmt.Println("body:", string(body)) |
| 58 |
} |
| 59 |
``` |
| 60 |
|
| 61 |
Speed compared to standard library `DefaultTransport` for an approximate 127KB JSON payload: |
| 62 |
|
| 63 |
``` |
| 64 |
BenchmarkTransport |
| 65 |
|
| 66 |
Single core: |
| 67 |
BenchmarkTransport/gzhttp-32 1995 609791 ns/op 214.14 MB/s 10129 B/op 73 allocs/op |
| 68 |
BenchmarkTransport/stdlib-32 1567 772161 ns/op 169.11 MB/s 53950 B/op 99 allocs/op |
| 69 |
BenchmarkTransport/zstd-32 4579 238503 ns/op 547.51 MB/s 5775 B/op 69 allocs/op |
| 70 |
|
| 71 |
Multi Core: |
| 72 |
BenchmarkTransport/gzhttp-par-32 29113 36802 ns/op 3548.27 MB/s 11061 B/op 73 allocs/op |
| 73 |
BenchmarkTransport/stdlib-par-32 16114 66442 ns/op 1965.38 MB/s 54971 B/op 99 allocs/op |
| 74 |
BenchmarkTransport/zstd-par-32 90177 13110 ns/op 9960.83 MB/s 5361 B/op 67 allocs/op |
| 75 |
``` |
| 76 |
|
| 77 |
This includes both serving the http request, parsing requests and decompressing. |
| 78 |
|
| 79 |
### Server |
| 80 |
|
| 81 |
For the simplest usage call `GzipHandler` with any handler (an object which implements the |
| 82 |
`http.Handler` interface), and it'll return a new handler which gzips the |
| 83 |
response. For example: |
| 84 |
|
| 85 |
```go |
| 86 |
package main |
| 87 |
|
| 88 |
import ( |
| 89 |
"io" |
| 90 |
"net/http" |
| 91 |
"github.com/klauspost/compress/gzhttp" |
| 92 |
) |
| 93 |
|
| 94 |
func main() { |
| 95 |
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 96 |
w.Header().Set("Content-Type", "text/plain") |
| 97 |
io.WriteString(w, "Hello, World") |
| 98 |
}) |
| 99 |
|
| 100 |
http.Handle("/", gzhttp.GzipHandler(handler)) |
| 101 |
http.ListenAndServe("0.0.0.0:8000", nil) |
| 102 |
} |
| 103 |
``` |
| 104 |
|
| 105 |
This will wrap a handler using the default options. |
| 106 |
|
| 107 |
To specify custom options a reusable wrapper can be created that can be used to wrap |
| 108 |
any number of handlers. |
| 109 |
|
| 110 |
```Go |
| 111 |
package main |
| 112 |
|
| 113 |
import ( |
| 114 |
"io" |
| 115 |
"log" |
| 116 |
"net/http" |
| 117 |
|
| 118 |
"github.com/klauspost/compress/gzhttp" |
| 119 |
"github.com/klauspost/compress/gzip" |
| 120 |
) |
| 121 |
|
| 122 |
func main() { |
| 123 |
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 124 |
w.Header().Set("Content-Type", "text/plain") |
| 125 |
io.WriteString(w, "Hello, World") |
| 126 |
}) |
| 127 |
|
| 128 |
// Create a reusable wrapper with custom options. |
| 129 |
wrapper, err := gzhttp.NewWrapper(gzhttp.MinSize(2000), gzhttp.CompressionLevel(gzip.BestSpeed)) |
| 130 |
if err != nil { |
| 131 |
log.Fatalln(err) |
| 132 |
} |
| 133 |
|
| 134 |
http.Handle("/", wrapper(handler)) |
| 135 |
http.ListenAndServe("0.0.0.0:8000", nil) |
| 136 |
} |
| 137 |
|
| 138 |
``` |
| 139 |
|
| 140 |
### Zstd Compression |
| 141 |
|
| 142 |
Zstd compression is enabled by default alongside gzip. When the client supports both, |
| 143 |
zstd is preferred because it typically offers better compression ratios and faster decompression. |
| 144 |
|
| 145 |
The server uses `Accept-Encoding` header negotiation to select the best encoding: |
| 146 |
- If client only accepts `gzip` → response is gzip compressed |
| 147 |
- If client only accepts `zstd` → response is zstd compressed |
| 148 |
- If client accepts both with equal qvalues → zstd is used (configurable) |
| 149 |
- If client specifies qvalues (e.g., `gzip;q=1.0, zstd;q=0.5`) → higher qvalue wins |
| 150 |
|
| 151 |
#### Zstd Options |
| 152 |
|
| 153 |
```Go |
| 154 |
// Disable zstd, only use gzip |
| 155 |
wrapper, _ := gzhttp.NewWrapper(gzhttp.EnableZstd(false)) |
| 156 |
|
| 157 |
// Disable gzip, only use zstd |
| 158 |
wrapper, _ := gzhttp.NewWrapper(gzhttp.EnableGzip(false)) |
| 159 |
|
| 160 |
// Prefer gzip when client accepts both with equal qvalues |
| 161 |
wrapper, _ := gzhttp.NewWrapper(gzhttp.PreferZstd(false)) |
| 162 |
|
| 163 |
// Set zstd compression level (1=fastest, 2=default, 3=better, 4=best) |
| 164 |
wrapper, _ := gzhttp.NewWrapper(gzhttp.ZstdCompressionLevel(int(zstd.SpeedDefault))) |
| 165 |
|
| 166 |
// Use custom zstd writer implementation |
| 167 |
wrapper, _ := gzhttp.NewWrapper(gzhttp.ZstdImplementation(myZstdFactory)) |
| 168 |
``` |
| 169 |
|
| 170 |
Default zstd settings are conservative for broad compatibility: |
| 171 |
- Level: `SpeedFastest` (1) - maximum speed |
| 172 |
- Window size: 128KB - minimal memory usage |
| 173 |
- Concurrency: 1 - single-threaded per request |
| 174 |
|
| 175 |
### Performance |
| 176 |
|
| 177 |
#### Gzip vs Zstd |
| 178 |
|
| 179 |
Zstd is significantly faster than gzip at default settings while providing similar or better compression: |
| 180 |
|
| 181 |
``` |
| 182 |
Single-threaded performance (2KB, 20KB, 100KB payload): |
| 183 |
BenchmarkGzipHandler_S2k 137.22 MB/s 3532 B/op 15 allocs/op |
| 184 |
BenchmarkZstdHandler_S2k 219.21 MB/s 1936 B/op 12 allocs/op (1.6x faster, 45% less memory) |
| 185 |
|
| 186 |
BenchmarkGzipHandler_S20k 306.91 MB/s 18616 B/op 18 allocs/op |
| 187 |
BenchmarkZstdHandler_S20k 434.05 MB/s 7595 B/op 12 allocs/op (1.4x faster, 59% less memory) |
| 188 |
|
| 189 |
BenchmarkGzipHandler_S100k 198.96 MB/s 66937 B/op 20 allocs/op |
| 190 |
BenchmarkZstdHandler_S100k 368.70 MB/s 63021 B/op 16 allocs/op (1.9x faster) |
| 191 |
|
| 192 |
Parallel performance: |
| 193 |
BenchmarkGzipHandler_P2k 997.01 MB/s 3148 B/op 15 allocs/op |
| 194 |
BenchmarkZstdHandler_P2k 1440.12 MB/s 1985 B/op 12 allocs/op (1.4x faster) |
| 195 |
|
| 196 |
BenchmarkGzipHandler_P20k 2129.70 MB/s 17572 B/op 18 allocs/op |
| 197 |
BenchmarkZstdHandler_P20k 2928.82 MB/s 7498 B/op 12 allocs/op (1.4x faster) |
| 198 |
|
| 199 |
BenchmarkGzipHandler_P100k 1678.72 MB/s 67316 B/op 20 allocs/op |
| 200 |
BenchmarkZstdHandler_P100k 2392.23 MB/s 61122 B/op 16 allocs/op (1.4x faster) |
| 201 |
``` |
| 202 |
|
| 203 |
#### Comparison to nytimes/gziphandler |
| 204 |
|
| 205 |
Speed compared to [nytimes/gziphandler](https://github.com/nytimes/gziphandler) with default settings, 2KB, 20KB and 100KB: |
| 206 |
|
| 207 |
``` |
| 208 |
λ benchcmp before.txt after.txt |
| 209 |
benchmark old ns/op new ns/op delta |
| 210 |
BenchmarkGzipHandler_S2k-32 51302 23679 -53.84% |
| 211 |
BenchmarkGzipHandler_S20k-32 301426 156331 -48.14% |
| 212 |
BenchmarkGzipHandler_S100k-32 1546203 818981 -47.03% |
| 213 |
BenchmarkGzipHandler_P2k-32 3973 1522 -61.69% |
| 214 |
BenchmarkGzipHandler_P20k-32 20319 9397 -53.75% |
| 215 |
BenchmarkGzipHandler_P100k-32 96079 46361 -51.75% |
| 216 |
|
| 217 |
benchmark old MB/s new MB/s speedup |
| 218 |
BenchmarkGzipHandler_S2k-32 39.92 86.49 2.17x |
| 219 |
BenchmarkGzipHandler_S20k-32 67.94 131.00 1.93x |
| 220 |
BenchmarkGzipHandler_S100k-32 66.23 125.03 1.89x |
| 221 |
BenchmarkGzipHandler_P2k-32 515.44 1345.31 2.61x |
| 222 |
BenchmarkGzipHandler_P20k-32 1007.92 2179.47 2.16x |
| 223 |
BenchmarkGzipHandler_P100k-32 1065.79 2208.75 2.07x |
| 224 |
|
| 225 |
benchmark old allocs new allocs delta |
| 226 |
BenchmarkGzipHandler_S2k-32 22 16 -27.27% |
| 227 |
BenchmarkGzipHandler_S20k-32 25 19 -24.00% |
| 228 |
BenchmarkGzipHandler_S100k-32 28 21 -25.00% |
| 229 |
BenchmarkGzipHandler_P2k-32 22 16 -27.27% |
| 230 |
BenchmarkGzipHandler_P20k-32 25 19 -24.00% |
| 231 |
BenchmarkGzipHandler_P100k-32 27 21 -22.22% |
| 232 |
|
| 233 |
benchmark old bytes new bytes delta |
| 234 |
BenchmarkGzipHandler_S2k-32 8836 2980 -66.27% |
| 235 |
BenchmarkGzipHandler_S20k-32 69034 20562 -70.21% |
| 236 |
BenchmarkGzipHandler_S100k-32 356582 86682 -75.69% |
| 237 |
BenchmarkGzipHandler_P2k-32 9062 2971 -67.21% |
| 238 |
BenchmarkGzipHandler_P20k-32 67799 20051 -70.43% |
| 239 |
BenchmarkGzipHandler_P100k-32 300972 83077 -72.40% |
| 240 |
``` |
| 241 |
|
| 242 |
### Stateless compression |
| 243 |
|
| 244 |
In cases where you expect to run many thousands of compressors concurrently, |
| 245 |
but with very little activity you can use stateless compression. |
| 246 |
This is not intended for regular web servers serving individual requests. |
| 247 |
|
| 248 |
Use `CompressionLevel(-3)` or `CompressionLevel(gzip.StatelessCompression)` to enable. |
| 249 |
Consider adding a [`bufio.Writer`](https://golang.org/pkg/bufio/#NewWriterSize) with a small buffer. |
| 250 |
|
| 251 |
See [more details on stateless compression](https://github.com/klauspost/compress#stateless-compression). |
| 252 |
|
| 253 |
### Migrating from gziphandler |
| 254 |
|
| 255 |
This package removes some of the extra constructors. |
| 256 |
When replacing, this can be used to find a replacement. |
| 257 |
|
| 258 |
* `GzipHandler(h)` -> `GzipHandler(h)` (keep as-is) |
| 259 |
* `GzipHandlerWithOpts(opts...)` -> `NewWrapper(opts...)` |
| 260 |
* `MustNewGzipLevelHandler(n)` -> `NewWrapper(CompressionLevel(n))` |
| 261 |
* `NewGzipLevelAndMinSize(n, s)` -> `NewWrapper(CompressionLevel(n), MinSize(s))` |
| 262 |
|
| 263 |
By default, some mime types will now be excluded. |
| 264 |
To re-enable compression of all types, use the `ContentTypeFilter(gzhttp.CompressAllContentTypeFilter)` option. |
| 265 |
|
| 266 |
### Range Requests |
| 267 |
|
| 268 |
Ranged requests are not well supported with compression. |
| 269 |
Therefore any request with a "Content-Range" header is not compressed. |
| 270 |
|
| 271 |
To signify that range requests are not supported any "Accept-Ranges" header set is removed when data is compressed. |
| 272 |
If you do not want this behavior use the `KeepAcceptRanges()` option. |
| 273 |
|
| 274 |
### Flushing data |
| 275 |
|
| 276 |
The wrapper supports the [http.Flusher](https://golang.org/pkg/net/http/#Flusher) interface. |
| 277 |
|
| 278 |
The only caveat is that the writer may not yet have received enough bytes to determine if `MinSize` |
| 279 |
has been reached. In this case it will assume that the minimum size has been reached. |
| 280 |
|
| 281 |
If nothing has been written to the response writer, nothing will be flushed. |
| 282 |
|
| 283 |
## BREACH mitigation |
| 284 |
|
| 285 |
[BREACH](http://css.csail.mit.edu/6.858/2020/readings/breach.pdf) is a specialized attack where attacker controlled data |
| 286 |
is injected alongside secret data in a response body. This can lead to sidechannel attacks, where observing the compressed response |
| 287 |
size can reveal if there are overlaps between the secret data and the injected data. |
| 288 |
|
| 289 |
For more information see https://breachattack.com/ |
| 290 |
|
| 291 |
It can be hard to judge if you are vulnerable to BREACH. |
| 292 |
In general, if you do not include any user provided content in the response body you are safe, |
| 293 |
but if you do, or you are in doubt, you can apply mitigations. |
| 294 |
|
| 295 |
`gzhttp` can apply [Heal the Breach](https://ieeexplore.ieee.org/document/9754554), or improved content aware padding. |
| 296 |
|
| 297 |
RandomJitter works with both gzip and zstd compression: |
| 298 |
- **gzip**: Jitter is added as a Comment field in the gzip header |
| 299 |
- **zstd**: Jitter is added as a skippable frame (RFC 8878 Section 3.1.2) after the compressed data |
| 300 |
|
| 301 |
```Go |
| 302 |
// RandomJitter adds 1->n random bytes to output based on checksum of payload. |
| 303 |
// Specify the amount of input to buffer before applying jitter. |
| 304 |
// This should cover the sensitive part of your response. |
| 305 |
// This can be used to obfuscate the exact compressed size. |
| 306 |
// Specifying 0 will use a buffer size of 64KB. |
| 307 |
// 'paranoid' will use a slower hashing function, that MAY provide more safety. |
| 308 |
// If a negative buffer is given, the amount of jitter will not be content dependent. |
| 309 |
// This provides *less* security than applying content based jitter. |
| 310 |
func RandomJitter(n, buffer int, paranoid bool) option |
| 311 |
... |
| 312 |
``` |
| 313 |
|
| 314 |
For gzip, the jitter is added as a "Comment" field with 1 byte overhead (actual extra size: 2 -> n+1 inclusive). |
| 315 |
For zstd, the jitter is added as a skippable frame with 8 byte overhead (actual extra size: 9 -> n+8 inclusive). |
| 316 |
|
| 317 |
A good option would be to apply 32 random bytes, with default 64KB buffer: `gzhttp.RandomJitter(32, 0, false)`. |
| 318 |
|
| 319 |
Note that flushing the data forces the padding to be applied, which means that only data before the flush is considered for content aware padding. |
| 320 |
|
| 321 |
The *padding* content is the text `Padding-Padding-Padding-Padding-Pad....` |
| 322 |
|
| 323 |
The *length* is `1 + crc32c(payload) MOD n` or `1 + sha256(payload) MOD n` (paranoid), or just random from `crypto/rand` if buffer < 0. |
| 324 |
|
| 325 |
### Paranoid? |
| 326 |
|
| 327 |
The padding size is determined by the remainder of a CRC32 of the content. |
| 328 |
|
| 329 |
Since the payload contains elements unknown to the attacker, there is no reason to believe they can derive any information |
| 330 |
from this remainder, or predict it. |
| 331 |
|
| 332 |
However, for those that feel uncomfortable with a CRC32 being used for this can enable "paranoid" mode which will use SHA256 for determining the padding. |
| 333 |
|
| 334 |
The hashing itself is about 2 orders of magnitude slower, but in overall terms will maybe only reduce speed by 10%. |
| 335 |
|
| 336 |
Paranoid mode has no effect if buffer is < 0 (non-content aware padding). |
| 337 |
|
| 338 |
### Examples |
| 339 |
|
| 340 |
Adding the option `gzhttp.RandomJitter(32, 50000)` will apply from 1 up to 32 bytes of random data to the output. |
| 341 |
|
| 342 |
The number of bytes added depends on the content of the first 50000 bytes, or all of them if the output was less than that. |
| 343 |
|
| 344 |
Adding the option `gzhttp.RandomJitter(32, -1)` will apply from 1 up to 32 bytes of random data to the output. |
| 345 |
Each call will apply a random amount of jitter. This should be considered less secure than content based jitter. |
| 346 |
|
| 347 |
This can be used if responses are very big, deterministic and the buffer size would be too big to cover where the mutation occurs. |
| 348 |
|
| 349 |
## License |
| 350 |
|
| 351 |
[Apache 2.0](LICENSE) |
| 352 |
|
| 353 |
|