Skip to main content

rama_http/layer/decompression/request/
layer.rs

1use super::service::RequestDecompression;
2use crate::headers::encoding::AcceptEncoding;
3use rama_core::Layer;
4
5/// Decompresses request bodies and calls its underlying service.
6///
7/// Transparently decompresses request bodies based on the `Content-Encoding` header.
8/// When the encoding in the `Content-Encoding` header is not accepted an `Unsupported Media Type`
9/// status code will be returned with the accepted encodings in the `Accept-Encoding` header.
10///
11/// Enabling pass-through of unaccepted encodings will not return an `Unsupported Media Type`. But
12/// will call the underlying service with the unmodified request if the encoding is not supported.
13/// This is disabled by default.
14///
15/// See the [module docs](crate::layer::decompression) for more details.
16#[derive(Debug, Default, Clone)]
17pub struct RequestDecompressionLayer {
18    accept: AcceptEncoding,
19    pass_through_unaccepted: bool,
20}
21
22impl<S> Layer<S> for RequestDecompressionLayer {
23    type Service = RequestDecompression<S>;
24
25    fn layer(&self, service: S) -> Self::Service {
26        RequestDecompression {
27            inner: service,
28            accept: self.accept,
29            pass_through_unaccepted: self.pass_through_unaccepted,
30        }
31    }
32}
33
34impl RequestDecompressionLayer {
35    /// Creates a new `RequestDecompressionLayer`.
36    #[must_use]
37    pub fn new() -> Self {
38        Default::default()
39    }
40
41    rama_utils::macros::generate_set_and_with! {
42        /// Sets whether to support gzip encoding.
43        pub fn gzip(mut self, enable: bool) -> Self {
44            self.accept.set_gzip(enable);
45            self
46        }
47    }
48
49    rama_utils::macros::generate_set_and_with! {
50        /// Sets whether to support Deflate encoding.
51        pub fn deflate(mut self, enable: bool) -> Self {
52            self.accept.set_deflate(enable);
53            self
54        }
55    }
56
57    rama_utils::macros::generate_set_and_with! {
58        /// Sets whether to support Brotli encoding.
59        pub fn br(mut self, enable: bool) -> Self {
60            self.accept.set_br(enable);
61            self
62        }
63    }
64
65    rama_utils::macros::generate_set_and_with! {
66        /// Sets whether to support Zstd encoding.
67        pub fn zstd(mut self, enable: bool) -> Self {
68            self.accept.set_zstd(enable);
69            self
70        }
71    }
72
73    rama_utils::macros::generate_set_and_with! {
74        /// Sets whether to pass through the request even when the encoding is not supported.
75        pub fn pass_through_unaccepted(mut self, enable: bool) -> Self {
76            self.pass_through_unaccepted = enable;
77            self
78        }
79    }
80}