hashira_rocket/
lib.rs

1use std::net::SocketAddr;
2
3use hashira::{adapter::Adapter, app::AppService, error::BoxError};
4use rocket::{Build, Rocket};
5
6pub mod core;
7
8pub struct HashiraRocket(Rocket<Build>);
9
10impl HashiraRocket {
11    pub fn new() -> HashiraRocket {
12        HashiraRocket(Rocket::build())
13    }
14}
15
16impl From<Rocket<Build>> for HashiraRocket {
17    fn from(value: Rocket<Build>) -> Self {
18        HashiraRocket(value)
19    }
20}
21
22impl Default for HashiraRocket {
23    fn default() -> Self {
24        Self::new()
25    }
26}
27
28#[hashira::async_trait]
29impl Adapter for HashiraRocket {
30    /// Starts the server.
31    async fn serve(self, app: AppService) -> Result<(), BoxError> {
32        let host = hashira::env::get_host().unwrap_or_else(|| String::from("127.0.0.1"));
33        let port = hashira::env::get_port().unwrap_or(5000);
34        let addr: SocketAddr = format!("{host}:{port}").as_str().parse().unwrap();
35
36        let shutdown = rocket::config::Shutdown {
37            ctrlc: false, // hashira cli handle the shutdown
38            ..rocket::config::Shutdown::default()
39        };
40
41        let mut rocket = self.0;
42
43        // Attach the router to the rocket
44        rocket = {
45            let configure = core::router(app);
46            configure(rocket)
47        };
48
49        let figment = rocket
50            .figment()
51            .clone()
52            .merge((rocket::Config::ADDRESS, addr.ip()))
53            .merge((rocket::Config::PORT, addr.port()))
54            .merge((rocket::Config::LOG_LEVEL, rocket::config::LogLevel::Off))
55            .merge((rocket::Config::SHUTDOWN, shutdown));
56
57        let rocket = rocket.configure(figment).ignite().await?;
58        println!("Server started at: http://{addr}");
59
60        // Start the server
61        rocket.launch().await?;
62
63        Ok(())
64    }
65}