Response Compression
warp can automatically compress response bodies to reduce the amount of data sent to the client, which can improve performance, especially on slow networks. It supports gzip, deflate, and brotli compression.
Enabling Compression Features
Compression is an optional feature. You need to enable the corresponding feature flags in your Cargo.toml.
[dependencies]
# The meta-feature enables both gzip and brotli
warp = { version = "0.4", features = ["compression"] }
# Or, you can enable them individually:
# warp = { version = "0.4", features = ["compression-gzip", "compression-brotli"] }
compression-gzip: Enablesgzipanddeflatecompression.compression-brotli: Enablesbrotlicompression.compression: Enables both of the above.
Applying Compression to a Route
Compression is applied as a wrapper using the .with() method on a filter. You can choose the compression algorithm to apply.
use warp::Filter;
// This route will have its response body compressed with gzip.
let file = warp::path("todos")
.and(warp::fs::file("./examples/todos.rs"))
.with(warp::compression::gzip());
// This route will compress responses with deflate.
let examples_dir = warp::path("ex")
.and(warp::fs::dir("./examples/"))
.with(warp::compression::deflate());
// This route will compress responses with brotli.
let readme = warp::path::end()
.and(warp::fs::file("./README.md"))
.with(warp::compression::brotli());
let routes = file.or(examples_dir).or(readme);
When a compression filter is applied, warp will:
- Compress the response body using the specified algorithm.
- Add the appropriate
Content-Encodingheader to the response (e.g.,content-encoding: gzip). - Remove the
Content-Lengthheader, as the final size is determined by the streaming compression.
Note: The client is responsible for sending an Accept-Encoding header indicating it can handle compressed content. However, warp's compression filters currently apply compression unconditionally. For more advanced content negotiation, you would need to implement additional filter logic.