64 lines
1.8 KiB
Rust
64 lines
1.8 KiB
Rust
use axum::{routing::get, Json, Router};
|
|
use std::{net::SocketAddr, sync::Arc};
|
|
use tokio::net::TcpListener;
|
|
use tracing::{info, level_filters::LevelFilter};
|
|
use tracing_subscriber::EnvFilter;
|
|
|
|
use api::services::{DefaultHealthService, HealthService};
|
|
use api::types::Health;
|
|
use api::config::AppSettings;
|
|
|
|
pub struct AppState {
|
|
pub health_service: Arc<dyn HealthService>,
|
|
}
|
|
|
|
pub async fn build_router(state: Arc<AppState>) -> Router {
|
|
Router::new().route(
|
|
"/health",
|
|
get({
|
|
let state = state.clone();
|
|
move || health_handler(state.clone())
|
|
}),
|
|
)
|
|
}
|
|
|
|
async fn health_handler(state: Arc<AppState>) -> Json<Health> {
|
|
let res = state.health_service.health().await;
|
|
Json(res)
|
|
}
|
|
|
|
pub async fn start_server(addr: SocketAddr) -> anyhow::Result<()> {
|
|
init_tracing();
|
|
|
|
// Load application settings and initialize the database pool (sqlite).
|
|
let app_settings = AppSettings::get_app_settings();
|
|
let pool = db::initialize_db(&app_settings).await?;
|
|
|
|
let state = Arc::new(AppState {
|
|
health_service: Arc::new(DefaultHealthService),
|
|
});
|
|
|
|
// Base daemon router
|
|
let app = build_router(state).await
|
|
// Attach API under /api and provide DB state
|
|
.nest("/api", api::api::routes::routes().with_state(pool.clone()));
|
|
|
|
let listener = TcpListener::bind(addr).await?;
|
|
info!("HTTP server listening on http://{}", addr);
|
|
axum::serve(listener, app).await?;
|
|
Ok(())
|
|
}
|
|
|
|
fn init_tracing() {
|
|
let env_filter = EnvFilter::try_from_default_env()
|
|
.or_else(|_| EnvFilter::try_new("info"))
|
|
.unwrap()
|
|
.add_directive(LevelFilter::INFO.into());
|
|
|
|
tracing_subscriber::fmt()
|
|
.with_env_filter(env_filter)
|
|
.with_target(true)
|
|
.compact()
|
|
.init();
|
|
}
|