Skip to main content

serenade_http/
kernel.rs

1//! HTTP kernel: middleware pipeline plus exception mapping.
2
3use crate::{
4    DefaultExceptionHandler, ExceptionHandler, HttpError, Middleware, Request, RequestHandler,
5    Response,
6};
7
8/// Runs middleware, then the controller, and maps errors to responses.
9///
10/// # Examples
11///
12/// ```
13/// use serenade_http::{HttpKernel, Method, Request, Response};
14///
15/// let kernel = HttpKernel::new(|_request: &mut Request| Ok(Response::text(200, "ok")));
16/// let response = kernel.handle(Request::new(Method::Get, "/healthz"));
17/// assert_eq!(response.status(), 200);
18/// assert_eq!(response.body_str(), Some("ok"));
19/// ```
20pub struct HttpKernel {
21    middleware: Vec<Box<dyn Middleware>>,
22    controller: Box<dyn RequestHandler>,
23    exceptions: Box<dyn ExceptionHandler>,
24}
25
26impl HttpKernel {
27    /// Kernel with `controller` and [`DefaultExceptionHandler`]. No middleware.
28    #[must_use]
29    pub fn new(controller: impl RequestHandler + 'static) -> Self {
30        Self {
31            middleware: Vec::new(),
32            controller: Box::new(controller),
33            exceptions: Box::new(DefaultExceptionHandler),
34        }
35    }
36
37    /// Replaces the exception mapper.
38    #[must_use]
39    pub fn with_exception_handler(mut self, handler: impl ExceptionHandler + 'static) -> Self {
40        self.exceptions = Box::new(handler);
41        self
42    }
43
44    /// Appends middleware. The first pushed layer is outermost (runs first).
45    pub fn push_middleware(&mut self, middleware: impl Middleware + 'static) -> &mut Self {
46        self.middleware.push(Box::new(middleware));
47        self
48    }
49
50    /// Handles `request` and always returns a [`Response`].
51    #[must_use]
52    pub fn handle(&self, mut request: Request) -> Response {
53        match self.dispatch(&mut request) {
54            Ok(response) => response,
55            Err(error) => self.exceptions.handle(&error),
56        }
57    }
58
59    fn dispatch(&self, request: &mut Request) -> Result<Response, HttpError> {
60        Tail {
61            middleware: &self.middleware,
62            controller: self.controller.as_ref(),
63        }
64        .handle(request)
65    }
66}
67
68struct Tail<'mw> {
69    middleware: &'mw [Box<dyn Middleware>],
70    controller: &'mw dyn RequestHandler,
71}
72
73impl RequestHandler for Tail<'_> {
74    fn handle(&self, request: &mut Request) -> Result<Response, HttpError> {
75        match self.middleware.split_first() {
76            Some((head, rest)) => head.process(
77                request,
78                &Tail {
79                    middleware: rest,
80                    controller: self.controller,
81                },
82            ),
83            None => self.controller.handle(request),
84        }
85    }
86}