Failed to call async function in custom middleware #1802
-
I'm to implement a custom authentication middleware, which read params in query string and check in database. I couldn't find any example to achive this. I work around to implement by self but failed with lifetime issue. Is there anything I'm missing, or currently not possible yet? impl<S, B> Transform<S> for FuncMiddleware<S>
where
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = actix_web::Error>,
S::Future: 'static,
B: MessageBody
{
// whatever codes...
}
pub struct FuncMiddlewareFuture<S> {
service: S,
}
impl<S, B> Service for FuncMiddlewareFuture<S>
where
S: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = actix_web::Error>,
S::Future: 'static,
B: MessageBody,
{
type Request = ServiceRequest;
type Response = ServiceResponse<B>;
type Error = actix_web::Error;
type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>>>>;
fn poll_ready(&mut self, ctx: &mut task::Context<'_>) -> Poll<Result<(), Self::Error>> {
self.service.poll_ready(ctx)
}
fn call(&mut self, req: Self::Request) -> Self::Future {
Box::pin(async move {
if async_function().await {
let response = self.service.call(req).await?;
Ok(response)
} else {
Err(actix_web::error::ErrorForbidden(Error::AccessDeny))
}
})
}
}
async fn async_function() -> bool {
true
} Got error:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Since the returned future needs to be 'static, everything in the async move block needs to be owned/cloned. A common pattern to work around the lifetime issues is to use an An example from the httpauth middleware: https://github.com/actix/actix-extras/blob/f970d908943126e505a5cb58a3af9aece7926e00/actix-web-httpauth/src/middleware.rs#L177. |
Beta Was this translation helpful? Give feedback.
Since the returned future needs to be 'static, everything in the async move block needs to be owned/cloned. A common pattern to work around the lifetime issues is to use an
Rc<RefCell<S>>
in the service.An example from the httpauth middleware: https://github.com/actix/actix-extras/blob/f970d908943126e505a5cb58a3af9aece7926e00/actix-web-httpauth/src/middleware.rs#L177.