summaryrefslogtreecommitdiffstats
path: root/src/routes.rs
blob: 3625eff6d1891410488488ed35486ccec65059fe (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
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 => {},
    }
}