Skip to content

Commit 0cb453e

Browse files
committed
feat(encoding): use an extension for encoding, which allow a specific handler to disable compression if needed
1 parent 8115c81 commit 0cb453e

File tree

1 file changed

+30
-9
lines changed

1 file changed

+30
-9
lines changed

actix-web/src/middleware/compress.rs

+30-9
Original file line numberDiff line numberDiff line change
@@ -110,14 +110,22 @@ where
110110

111111
#[allow(clippy::borrow_interior_mutable_const)]
112112
fn call(&self, req: ServiceRequest) -> Self::Future {
113+
if req.extensions().get::<Encoding>().is_some() {
114+
return Either::left(CompressResponse {
115+
fut: self.service.call(req),
116+
_phantom: PhantomData,
117+
});
118+
}
119+
113120
// negotiate content-encoding
114121
let accept_encoding = req.get_header::<AcceptEncoding>();
115122

116123
let accept_encoding = match accept_encoding {
117124
// missing header; fallback to identity
118125
None => {
126+
req.extensions_mut().insert::<Encoding>(Encoding::identity());
127+
119128
return Either::left(CompressResponse {
120-
encoding: Encoding::identity(),
121129
fut: self.service.call(req),
122130
_phantom: PhantomData,
123131
})
@@ -143,11 +151,14 @@ where
143151
.map_into_right_body()))
144152
}
145153

146-
Some(encoding) => Either::left(CompressResponse {
147-
fut: self.service.call(req),
148-
encoding,
149-
_phantom: PhantomData,
150-
}),
154+
Some(encoding) => {
155+
req.extensions_mut().insert::<Encoding>(encoding);
156+
157+
Either::left(CompressResponse {
158+
fut: self.service.call(req),
159+
_phantom: PhantomData,
160+
})
161+
},
151162
}
152163
}
153164
}
@@ -159,7 +170,6 @@ pin_project! {
159170
{
160171
#[pin]
161172
fut: S::Future,
162-
encoding: Encoding,
163173
_phantom: PhantomData<B>,
164174
}
165175
}
@@ -176,8 +186,19 @@ where
176186

177187
match ready!(this.fut.poll(cx)) {
178188
Ok(resp) => {
179-
let enc = match this.encoding {
180-
Encoding::Known(enc) => *enc,
189+
let request_encoding = resp.request().extensions().get::<Encoding>().cloned();
190+
191+
let encoding = match request_encoding {
192+
Some(enc) => enc.clone(),
193+
None => {
194+
return Poll::Ready(Ok(resp.map_body(move |head, body| {
195+
EitherBody::left(Encoder::response(ContentEncoding::Identity, head, body))
196+
})));
197+
}
198+
};
199+
200+
let enc = match encoding {
201+
Encoding::Known(enc) => enc,
181202
Encoding::Unknown(enc) => {
182203
unimplemented!("encoding '{enc}' should not be here");
183204
}

0 commit comments

Comments
 (0)