From b94f8e694bf01f5dba9ce2c01f589463a3dfbc69 Mon Sep 17 00:00:00 2001 From: Toby Vincent Date: Wed, 9 Oct 2024 18:23:58 -0500 Subject: feat!: rewrite to use traits and streams --- src/main.rs | 39 ++++++++++++++++----------------------- 1 file changed, 16 insertions(+), 23 deletions(-) (limited to 'src/main.rs') diff --git a/src/main.rs b/src/main.rs index fbf27cb..46adbfa 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,14 +1,10 @@ -use std::{collections::HashMap, fs::File, path::PathBuf, sync::Arc}; +use std::{collections::HashMap, fs::File, path::PathBuf}; + use tower_http::services::ServeDir; use tracing::level_filters::LevelFilter; use tracing_subscriber::EnvFilter; -use statsrv::service::Service; - -#[cfg(not(debug_assertions))] -const DEFAULT_CONFIG: &str = "/etc/statsrv.toml"; -#[cfg(debug_assertions)] -const DEFAULT_CONFIG: &str = "./config.toml"; +use statsrv::{service::ServiceConfig, AppState}; #[tokio::main] async fn main() -> Result<(), Box> { @@ -20,20 +16,14 @@ async fn main() -> Result<(), Box> { let config = match Config::parse() { Ok(c) => c, Err(err) => { - tracing::debug!("Failed to read config file: `{err}`"); - tracing::debug!("Using default config values"); + tracing::error!("Failed to read config file, using defaults: `{err}`"); Default::default() } }; - let state = config - .services - .into_iter() - .map(|(name, service)| (name, service.into())) - .collect(); - + let state = AppState::spawn_services(config.services); let router = statsrv::router() - .with_state(Arc::new(state)) + .with_state(state) .nest_service("/", ServeDir::new(config.root)) .layer(tower_http::trace::TraceLayer::new_for_http()); @@ -48,17 +38,20 @@ async fn main() -> Result<(), Box> { pub struct Config { pub root: PathBuf, pub address: String, - pub services: HashMap, + pub services: HashMap, } impl Config { - fn parse() -> Result> { - let config_path = std::env::args().nth(1).unwrap_or_else(|| { - tracing::debug!("Falling back to default config location"); - DEFAULT_CONFIG.to_string() - }); + const DEFAULT_CONFIG: &str = "/etc/statsrv.toml"; - let config_file = File::open(&config_path)?; + fn parse() -> Result> { + let config_file = match std::env::args().nth(1) { + Some(p) => File::open(&p)?, + None => { + tracing::debug!("Falling back to default config location"); + File::open(Self::DEFAULT_CONFIG)? + } + }; let config_toml = std::io::read_to_string(config_file)?; toml::from_str(&config_toml).map_err(Into::into) } -- cgit v1.2.3-70-g09d2