Skip to main content

loco_rs/controller/middleware/
fallback.rs

1//! Fallback Middleware
2//!
3//! This middleware handles fallback logic for the application when routes do
4//! not match. It serves a file, a custom not-found message, or a default HTML
5//! fallback page based on the configuration.
6
7use axum::{
8    extract::Request,
9    http::StatusCode,
10    response::{Html, IntoResponse},
11    Router as AXRouter,
12};
13use serde::{Deserialize, Deserializer, Serialize, Serializer};
14use tower::Service;
15use tower_http::services::ServeFile;
16
17use crate::{app::AppContext, controller::middleware::MiddlewareLayer, Result};
18
19#[derive(Debug)]
20pub struct StatusCodeWrapper(pub StatusCode);
21
22#[derive(Debug, Clone, Deserialize, Serialize)]
23pub struct Fallback {
24    /// By default when enabled, returns a prebaked 404 not found page optimized
25    /// for development. For production set something else (see fields below)
26    #[serde(default)]
27    pub enable: bool,
28    /// For the unlikely reason to return something different than `404`, you
29    /// can set it here
30    #[serde(
31        default = "default_status_code",
32        serialize_with = "serialize_status_code",
33        deserialize_with = "deserialize_status_code"
34    )]
35    pub code: StatusCode,
36    /// Returns content from a file pointed to by this field, with the status
37    /// in `code` (`404` unless you set it).
38    pub file: Option<String>,
39    /// Returns a "404 not found" with a single message string. This sets the
40    /// message.
41    pub not_found: Option<String>,
42}
43
44fn default_status_code() -> StatusCode {
45    StatusCode::NOT_FOUND
46}
47
48impl Default for Fallback {
49    fn default() -> Self {
50        super::defaults()
51    }
52}
53
54fn deserialize_status_code<'de, D>(de: D) -> Result<StatusCode, D::Error>
55where
56    D: Deserializer<'de>,
57{
58    let code: u16 = Deserialize::deserialize(de)?;
59    StatusCode::from_u16(code).map_or_else(
60        |_| {
61            Err(serde::de::Error::invalid_value(
62                serde::de::Unexpected::Unsigned(u64::from(code)),
63                &"a value between 100 and 600",
64            ))
65        },
66        Ok,
67    )
68}
69
70#[allow(clippy::trivially_copy_pass_by_ref)]
71fn serialize_status_code<S>(status: &StatusCode, ser: S) -> Result<S::Ok, S::Error>
72where
73    S: Serializer,
74{
75    ser.serialize_u16(status.as_u16())
76}
77impl MiddlewareLayer for Fallback {
78    /// Returns the name of the middleware
79    fn name(&self) -> &'static str {
80        "fallback"
81    }
82
83    /// Returns whether the middleware is enabled or not
84    fn is_enabled(&self) -> bool {
85        self.enable
86    }
87
88    fn config(&self) -> serde_json::Result<serde_json::Value> {
89        serde_json::to_value(self)
90    }
91
92    /// Applies the fallback middleware to the application router.
93    fn apply(&self, app: AXRouter<AppContext>) -> Result<AXRouter<AppContext>> {
94        let app = if let Some(path) = &self.file {
95            let path = path.clone();
96            let status_code = self.code;
97            app.fallback(move |req: Request| async move {
98                // `ServeFile` answers 200 for a file it finds; an unmatched
99                // route must still answer with the configured code, like
100                // Rails serving `public/404.html`. Reading the file on each
101                // request lets you edit it without restarting.
102                let mut res = ServeFile::new(path).call(req).await.into_response();
103                if res.status().is_success() {
104                    *res.status_mut() = status_code;
105                }
106                res
107            })
108        } else if let Some(not_found) = &self.not_found {
109            let not_found = not_found.clone();
110            let status_code = self.code;
111            app.fallback(move || async move { (status_code, not_found) })
112        } else {
113            let content = include_str!("fallback.html");
114            let status_code = self.code;
115            app.fallback(move || async move { (status_code, Html(content)) })
116        };
117        Ok(app)
118    }
119}
120
121#[cfg(test)]
122mod tests {
123    use super::*;
124
125    #[test]
126    fn default_code_is_not_found() {
127        assert_eq!(Fallback::default().code, StatusCode::NOT_FOUND);
128    }
129}