1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
use super::{CompressionBody, CompressionLayer, ResponseFuture};
use crate::compression::predicate::{DefaultPredicate, Predicate};
use crate::{compression_utils::AcceptEncoding, content_encoding::Encoding};
use http::{Request, Response};
use http_body::Body;
use std::task::{Context, Poll};
use tower_service::Service;
#[derive(Clone, Copy)]
pub struct Compression<S, P = DefaultPredicate> {
pub(crate) inner: S,
pub(crate) accept: AcceptEncoding,
pub(crate) predicate: P,
}
impl<S> Compression<S, DefaultPredicate> {
pub fn new(service: S) -> Compression<S, DefaultPredicate> {
Self {
inner: service,
accept: AcceptEncoding::default(),
predicate: DefaultPredicate::default(),
}
}
}
impl<S, P> Compression<S, P> {
define_inner_service_accessors!();
pub fn layer() -> CompressionLayer {
CompressionLayer::new()
}
#[cfg(feature = "compression-gzip")]
#[cfg_attr(docsrs, doc(cfg(feature = "compression-gzip")))]
pub fn gzip(mut self, enable: bool) -> Self {
self.accept.set_gzip(enable);
self
}
#[cfg(feature = "compression-deflate")]
#[cfg_attr(docsrs, doc(cfg(feature = "compression-deflate")))]
pub fn deflate(mut self, enable: bool) -> Self {
self.accept.set_deflate(enable);
self
}
#[cfg(feature = "compression-br")]
#[cfg_attr(docsrs, doc(cfg(feature = "compression-br")))]
pub fn br(mut self, enable: bool) -> Self {
self.accept.set_br(enable);
self
}
pub fn no_gzip(mut self) -> Self {
self.accept.set_gzip(false);
self
}
pub fn no_deflate(mut self) -> Self {
self.accept.set_deflate(false);
self
}
pub fn no_br(mut self) -> Self {
self.accept.set_br(false);
self
}
pub fn compress_when<C>(self, predicate: C) -> Compression<S, C>
where
C: Predicate,
{
Compression {
inner: self.inner,
accept: self.accept,
predicate,
}
}
}
impl<ReqBody, ResBody, S, P> Service<Request<ReqBody>> for Compression<S, P>
where
S: Service<Request<ReqBody>, Response = Response<ResBody>>,
ResBody: Body,
P: Predicate,
{
type Response = Response<CompressionBody<ResBody>>;
type Error = S::Error;
type Future = ResponseFuture<S::Future, P>;
#[inline]
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.inner.poll_ready(cx)
}
fn call(&mut self, req: Request<ReqBody>) -> Self::Future {
let encoding = Encoding::from_headers(req.headers(), self.accept);
ResponseFuture {
inner: self.inner.call(req),
encoding,
predicate: self.predicate.clone(),
}
}
}