serenade_http/
async_kernel.rs1use crate::{
4 AsyncMiddleware, AsyncNext, AsyncRequestHandler, BoxFuture, DefaultExceptionHandler,
5 ExceptionHandler, HttpError, Request, Response, SyncToAsync,
6};
7
8pub struct AsyncHttpKernel {
20 middleware: Vec<Box<dyn AsyncMiddleware>>,
21 controller: Box<dyn AsyncRequestHandler>,
22 exceptions: Box<dyn ExceptionHandler>,
23}
24
25impl AsyncHttpKernel {
26 #[must_use]
28 pub fn new(controller: impl AsyncRequestHandler + 'static) -> Self {
29 Self {
30 middleware: Vec::new(),
31 controller: Box::new(controller),
32 exceptions: Box::new(DefaultExceptionHandler),
33 }
34 }
35
36 #[must_use]
38 pub fn from_async_fn<F>(handler: F) -> Self
39 where
40 F: for<'req> Fn(&'req mut Request) -> BoxFuture<'req, Result<Response, HttpError>>
41 + Send
42 + Sync
43 + 'static,
44 {
45 Self::new(crate::AsyncFn(handler))
46 }
47
48 #[must_use]
50 pub fn from_sync(controller: impl crate::RequestHandler + 'static) -> Self {
51 Self::new(SyncToAsync(controller))
52 }
53
54 #[must_use]
56 pub fn with_exception_handler(mut self, handler: impl ExceptionHandler + 'static) -> Self {
57 self.exceptions = Box::new(handler);
58 self
59 }
60
61 pub fn push_middleware(&mut self, middleware: impl AsyncMiddleware + 'static) -> &mut Self {
63 self.middleware.push(Box::new(middleware));
64 self
65 }
66
67 #[must_use = "futures do nothing unless you await them"]
69 pub fn handle(&self, mut request: Request) -> BoxFuture<'_, Response> {
70 Box::pin(async move {
71 match self.dispatch(&mut request).await {
72 Ok(response) => response,
73 Err(error) => self.exceptions.handle(&error),
74 }
75 })
76 }
77
78 fn dispatch<'req>(
79 &'req self,
80 request: &'req mut Request,
81 ) -> BoxFuture<'req, Result<Response, HttpError>> {
82 AsyncNext {
83 middleware: &self.middleware,
84 controller: self.controller.as_ref(),
85 }
86 .run(request)
87 }
88}