http_response_compression/
layer.rs

1use crate::service::CompressionService;
2use tower::Layer;
3
4/// Default minimum body size for compression (approximately 1 MTU).
5pub const DEFAULT_MIN_SIZE: usize = 860;
6
7/// A Tower layer that compresses HTTP response bodies.
8///
9/// This layer wraps services and automatically compresses response bodies
10/// based on the client's Accept-Encoding header.
11#[derive(Debug, Clone)]
12pub struct CompressionLayer {
13    min_size: usize,
14}
15
16impl CompressionLayer {
17    /// Creates a new compression layer with default settings.
18    ///
19    /// The default minimum size for compression is 860 bytes.
20    pub fn new() -> Self {
21        Self {
22            min_size: DEFAULT_MIN_SIZE,
23        }
24    }
25
26    /// Sets the minimum body size required for compression.
27    ///
28    /// Responses with a known Content-Length smaller than this value
29    /// will not be compressed.
30    pub fn min_size(mut self, size: usize) -> Self {
31        self.min_size = size;
32        self
33    }
34}
35
36impl Default for CompressionLayer {
37    fn default() -> Self {
38        Self::new()
39    }
40}
41
42impl<S> Layer<S> for CompressionLayer {
43    type Service = CompressionService<S>;
44
45    fn layer(&self, inner: S) -> Self::Service {
46        CompressionService::new(inner, self.min_size)
47    }
48}