limiting_factor_axum/
app.rs

1/*  -------------------------------------------------------------
2    Limiting Factor :: axum :: App
3    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
4    Project:        Nasqueron
5    License:        BSD-2-Clause
6    -------------------------------------------------------------    */
7
8use axum::Router;
9use log::{error, info};
10use tokio::net::TcpListener;
11
12/*  -------------------------------------------------------------
13    Re-exports from core
14    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -    */
15
16pub use limiting_factor_core::app::ServerConfig;
17
18/*  -------------------------------------------------------------
19    Main application server
20    - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -    */
21
22pub struct App {
23    pub config: ServerConfig,
24
25    router: Router,
26}
27
28impl Default for App {
29    fn default() -> Self {
30        Self {
31            config: ServerConfig::from_env(),
32            router: Router::new(),
33        }
34    }
35}
36
37impl App {
38    pub fn new (config: ServerConfig, router: Router) -> Self {
39        Self {
40            config,
41            router,
42        }
43    }
44
45    pub fn from_config(config: ServerConfig) -> Self {
46        Self {
47            config,
48            router: Router::new(),
49        }
50    }
51
52    pub fn with_config(mut self, config: ServerConfig) -> Self {
53        self.config = config;
54
55        self
56    }
57
58    pub fn from_router(router: Router) -> Self {
59        Self {
60            config: ServerConfig::from_env(),
61            router,
62        }
63    }
64
65    fn resolve_router(&self) -> Router {
66        if self.config.mount_point == "/" {
67            return self.router.clone();
68        }
69
70        Router::new()
71            .nest(&*self.config.mount_point, self.router.clone())
72    }
73
74    pub async fn run(self) -> bool {
75        let app = self.resolve_router();
76        let socket_address = self.config.get_socket_address();
77
78        info!("🚀 Starting server");
79        match TcpListener::bind(&socket_address).await {
80            Ok(listener) => {
81                info!("Listening to {}", socket_address);
82                axum::serve(listener, app).await.unwrap();
83
84                true
85            }
86
87            Err(error) => {
88                error!("{}", error);
89
90                false
91            }
92        }
93    }
94}