Response middleware? #3945
-
Hi, Middlewares before the service (requests) are handled but I can't reuse the middleware strategy for the response because it expects a request type. How to do it? I don't wan't to clutter my service with this because it's a fragile approach (we can forget it or whatever reason); I have multiple servers and code reuse is important.
would be nice. Thanks! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
The service_fn(|req| {
let inner_fut = inner.call(req);
async move {
let resp = inner_fut.await?;
Ok(transform_resp(resp))
}
}); You can do similarly with There's several examples, such as in tower-http, here's just one of many: https://docs.rs/tower-http/latest/tower_http/map_response_body/index.html |
Beta Was this translation helpful? Give feedback.
The
Service
trait allows for handling the request and the response. For instance, if using a closure:You can do similarly with
impl<Req> Service<Req>
, or withLayer
.There's several examples, such as in tower-http, here's just one of many: https://docs.rs/tower-http/latest/tower_http/map_response_body/index.html