Middleware example for 4.0.0 #2597
-
I've been trying to add some middleware to my app in the beta version, but with the changes to Transform and Service the example in the docs is no longer helping me. I've looked at the new docs for the traits, I've managed to fix it but get stuck at the call function. the trait `std::convert::From<&BoxBody>` is not implemented for `actix_web::dev::Response<_> fn call(&self, req: ServiceRequest) -> Self::Future {
let is_logged_in = false;
if is_logged_in {
Either::Left(self.service.call(req))
}else {
Either::Right(ok(req.into_response(
HttpResponse::Ok().finish().body()
)
))
}
} I also noticed that actix-web now has Either, not sure if that replaces the futures::Either as well. |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 3 replies
-
You'll need type Response = ServiceResponse<EitherBody<B, BoxBody>>;
fn call() {
let service = Rc::clone(&self.service);
Box::pin(async move {
if true {
Ok(service.call(req)?.await.map_into_left_body())
} else {
let resp = HttpResponse::Ok().finish();
Ok(req.into_response(resp).map_into_right_body())
}
})
} alternatively you can box the response body: type Response = ServiceResponse<BoxBody>; // or `ServiceResponse`
fn call() {
let service = Rc::clone(&self.service);
Box::pin(async move {
if true {
Ok(service.call(req)?.await.map_into_boxed_body())
} else {
let resp = HttpResponse::Ok().finish();
Ok(req.into_response(resp).map_into_boxed_body())
}
})
} |
Beta Was this translation helpful? Give feedback.
-
In case this helps anyone else who stumbles here,
Really helpful capability! |
Beta Was this translation helpful? Give feedback.
-
This worked for me but I made my B bound by MessageBody. This is causing to infinite loop on poll_next. Anyone seeing this? |
Beta Was this translation helpful? Give feedback.
-
None of the comments here works for me to implement a simple middleware for actix_web 4. Not even a single working example exists on whole internet. |
Beta Was this translation helpful? Give feedback.
You'll need
EitherBody
andServiceResponse::{map_into_right_body, map_into_left_body}
alternatively you can box the response body: