use std::net::SocketAddr;
use sapphire_framework_keys::{AuthConfig, protect};
use tokio::task::JoinHandle;
use tokio_util::sync::CancellationToken;
pub(crate) async fn start(
addr: SocketAddr,
routes: axum::Router,
auth: AuthConfig,
stop: CancellationToken,
) -> Option<(SocketAddr, JoinHandle<()>)> {
let listener = match tokio::net::TcpListener::bind(addr).await {
Ok(listener) => listener,
Err(err) => {
tracing::error!("the HTTP listener could not bind {addr}: {err}");
return None;
}
};
let bound = listener.local_addr().unwrap_or(addr);
tracing::info!("serving HTTP on {bound}");
let app = protect(auth, routes);
let task = tokio::spawn(async move {
let served = axum::serve(listener, app)
.with_graceful_shutdown(async move { stop.cancelled().await })
.await;
if let Err(err) = served {
tracing::error!("the HTTP listener ended: {err}");
}
});
Some((bound, task))
}