From 3ca656997ec08d326f3bb2872f5338669ced47b9 Mon Sep 17 00:00:00 2001 From: Andrew Marcuse Date: Wed, 12 Feb 2025 09:25:03 -0500 Subject: [PATCH] Add signal handler for SIGINT and SIGTERM --- Cargo.toml | 1 + src/main.rs | 18 ++++++++++++++++-- 2 files changed, 17 insertions(+), 2 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 78dd25a..ea4b9b1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -15,3 +15,4 @@ serde = { version = "1.0.208", features = ["derive"] } serde_json = "1.0.125" tokio = { version = "1.39.2", features = ["full", "macros", "rt-multi-thread"] } tower-http = { version = "0.5.2", features = ["fs", "limit"] } +signal-hook = "0.3.13" diff --git a/src/main.rs b/src/main.rs index 313cd08..352fc7c 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,4 +1,3 @@ - use axum::{ body::Body, extract::{DefaultBodyLimit, Query}, response::{IntoResponse, Response}, routing::{get, post}, Json, Router }; @@ -9,8 +8,13 @@ use serde::{Deserialize, Serialize}; use tower_http::{limit::RequestBodyLimitLayer, services::ServeFile}; use html_escape::encode_text; +use signal_hook::consts::signal::{SIGINT, SIGTERM}; +use signal_hook_tokio::Signals; + #[tokio::main] async fn main() { + setup_signal_handlers().await; + // build our application with a single route let app = Router::new() //.route_service("/", get(|| async { axum::Redirect::temporary("https://www.regexplanet.com/advanced/rust/index.html") })) @@ -37,6 +41,16 @@ async fn main() { axum::serve(listener, app).await.unwrap(); } +async fn setup_signal_handlers() { + let signals = Signals::new(&[SIGINT, SIGTERM]).unwrap(); + tokio::spawn(async move { + for _ in signals.forever() { + println!("INFO: Received termination signal, shutting down..."); + std::process::exit(0); + } + }); +} + #[derive(Debug, Deserialize)] #[allow(dead_code)] struct StatusParams { @@ -302,4 +316,4 @@ fn handle_jsonp(callback: &str, html: String) -> Response { .body(Body::from(jsonp)) .unwrap(); } -} \ No newline at end of file +}