diff --git a/Cargo.toml b/Cargo.toml index eb5de6a..14ac365 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,7 +10,7 @@ readme = "README.md" [dependencies] axum = { version = "0.7.7", features = ["multipart"] } -tokio = { version = "1.41.1", features = ["full"] } +tokio = { version = "1.41.1", features = ["full", "signal"] } tower-http = { version = "0.6.1", features = ["fs"] } comrak = "0.29" serde = { version = "1.0.215", features = ["derive"] } diff --git a/src/main.rs b/src/main.rs index 7e4daf4..2bcadfb 100644 --- a/src/main.rs +++ b/src/main.rs @@ -114,18 +114,40 @@ async fn main() { .expect("Unable to parse socket address"); info!("Starting server on http://{}", addr); - match tokio::net::TcpListener::bind(&addr).await { - Ok(listener) => { - if let Err(e) = axum::serve(listener, app).await { - error!("Server error: {}", e); - } - } - Err(e) => { - error!("Failed to bind to address {}: {}", addr, e); + if let Ok(listener) = tokio::net::TcpListener::bind(&addr).await { + if let Err(e) = axum::serve(listener, app) + .with_graceful_shutdown(shutdown()) + .await + { + error!("Server error: {}", e); } } } +async fn shutdown() { + let ctrl_c = async { + tokio::signal::ctrl_c() + .await + .expect("Failed to install ctrl + c handler"); + }; + + #[cfg(unix)] + let terminate = async { + tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) + .expect("It's supposed to run in a unix system.") + .recv() + .await; + }; + + #[cfg(not(unix))] + let terminate = std::future::pending::<()>(); + + tokio::select! { + _ = ctrl_c => {}, + _ = terminate => {}, + } +} + fn load_notes(file: &PathBuf) -> Vec { if let Ok(content) = fs::read_to_string(file) { content