Skip to main content

serenade_http/
async_middleware.rs

1//! Async middleware around the controller pipeline.
2
3use crate::{AsyncRequestHandler, BoxFuture, HttpError, Request, Response};
4
5/// Remainder of the async middleware / controller stack.
6pub struct AsyncNext<'a> {
7    pub(crate) middleware: &'a [Box<dyn AsyncMiddleware>],
8    pub(crate) controller: &'a dyn AsyncRequestHandler,
9}
10
11impl<'a> AsyncNext<'a> {
12    /// Runs the next middleware or the controller.
13    pub fn run(self, request: &'a mut Request) -> BoxFuture<'a, Result<Response, HttpError>> {
14        match self.middleware.split_first() {
15            Some((head, rest)) => head.process(
16                request,
17                AsyncNext {
18                    middleware: rest,
19                    controller: self.controller,
20                },
21            ),
22            None => self.controller.handle(request),
23        }
24    }
25}
26
27/// Layer that may inspect or mutate the request, then await [`AsyncNext::run`].
28pub trait AsyncMiddleware: Send + Sync {
29    /// Runs this layer. Call `next.run(request).await` to continue the pipeline.
30    fn process<'a>(
31        &'a self,
32        request: &'a mut Request,
33        next: AsyncNext<'a>,
34    ) -> BoxFuture<'a, Result<Response, HttpError>>;
35}