Skip to main content

sword_layers/compression/
layer.rs

1use super::CompressionConfig;
2use tower_http::compression::CompressionLayer as TowerCompressionLayer;
3
4/// ### Compression Layer
5///
6/// This struct represents the Compression Layer which
7/// enables response compression based on the provided configuration.
8///
9/// The layer is a wrapper around `tower_http::compression::CompressionLayer`.
10/// Compress response bodies of the underlying service.
11///
12/// This uses the Accept-Encoding header to pick an appropriate encoding
13/// and adds the Content-Encoding header to responses.
14pub struct CompressionLayer;
15
16impl CompressionLayer {
17    pub fn new(config: &CompressionConfig) -> TowerCompressionLayer {
18        let mut layer = TowerCompressionLayer::new();
19
20        for algorithm in &config.algorithms {
21            match algorithm.to_lowercase().as_str() {
22                "gzip" => layer = layer.gzip(true),
23                "deflate" => layer = layer.deflate(true),
24                "br" | "brotli" => layer = layer.br(true),
25                "zstd" => layer = layer.zstd(true),
26                _ => {}
27            }
28        }
29
30        layer
31    }
32}