diff options
author | Toby Vincent <tobyv@tobyvin.dev> | 2024-03-20 14:22:24 -0500 |
---|---|---|
committer | Toby Vincent <tobyv@tobyvin.dev> | 2024-03-20 19:21:29 -0500 |
commit | f977dce01be9de61a64b94aab883fb43949234b3 (patch) | |
tree | e8b3b5b59b10d43619198ff7d0f9f0e10bed0818 /src/routes.rs |
chore: initial commit
Diffstat (limited to 'src/routes.rs')
-rw-r--r-- | src/routes.rs | 69 |
1 files changed, 69 insertions, 0 deletions
diff --git a/src/routes.rs b/src/routes.rs new file mode 100644 index 0000000..3625eff --- /dev/null +++ b/src/routes.rs @@ -0,0 +1,69 @@ +use axum::Router; +use axum_extra::routing::{RouterExt, TypedPath}; +use tokio::{ + net::{TcpListener, ToSocketAddrs}, + signal, +}; + +use crate::Error; + +#[derive(TypedPath)] +#[typed_path("/ping")] +pub struct Ping; + +/// # Test endpoint +/// +/// Returns "pong" +#[tracing::instrument(ret)] +pub async fn ping(_: Ping) -> &'static str { + "pong" +} + +#[derive(TypedPath)] +#[typed_path("/")] +pub struct Root; + +#[tracing::instrument(ret)] +pub async fn root(_: Root) -> &'static str { + "Hello, World!" +} + +pub async fn serve<A>(addr: A) -> Result<(), Error> +where + A: ToSocketAddrs, +{ + let app = Router::new().typed_get(root).typed_get(ping); + + let listener = TcpListener::bind(addr).await?; + + tracing::info!("Server listening on http://{}", listener.local_addr()?); + + axum::serve(listener, app) + .with_graceful_shutdown(shutdown_signal()) + .await + .map_err(From::from) +} + +async fn shutdown_signal() { + let ctrl_c = async { + signal::ctrl_c() + .await + .expect("failed to install Ctrl+C handler"); + }; + + #[cfg(unix)] + let terminate = async { + signal::unix::signal(signal::unix::SignalKind::terminate()) + .expect("failed to install signal handler") + .recv() + .await; + }; + + #[cfg(not(unix))] + let terminate = std::future::pending::<()>(); + + tokio::select! { + _ = ctrl_c => {}, + _ = terminate => {}, + } +} |