From 3402cb799d87f0d654eaad8c84492d91a289b3e6 Mon Sep 17 00:00:00 2001 From: Matthew Gordon Date: Mon, 12 Feb 2024 21:38:36 -0400 Subject: [PATCH] Move config into module and improve error handling --- src/config.rs | 26 ++++++++++++++++++++++++++ src/main.rs | 39 +++++++++++++++++++++++++++++++-------- 2 files changed, 57 insertions(+), 8 deletions(-) create mode 100644 src/config.rs diff --git a/src/config.rs b/src/config.rs new file mode 100644 index 0000000..75b026c --- /dev/null +++ b/src/config.rs @@ -0,0 +1,26 @@ +use {std::env, thiserror::Error}; + +const ENV_VAR_PREFIX: &str = "LOCALHUB_"; + +#[derive(Error, Debug)] +pub enum Error { + #[error("The environment variable \"{0}\" must be set.")] + MissingEnvironmentVariable(String), +} + +pub struct Config { + pub database_url: String, + pub static_file_path: String, +} + +fn get_config_string(variable: &str) -> Result { + let full_var = format!("{ENV_VAR_PREFIX}{variable}"); + env::var(&full_var).map_err(|_| Error::MissingEnvironmentVariable(full_var)) +} + +pub fn get_config() -> Result { + Ok(Config { + database_url: get_config_string("DATABASE_URL")?, + static_file_path: get_config_string("STATIC_FILE_PATH")?, + }) +} diff --git a/src/main.rs b/src/main.rs index c725408..748d7f9 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,24 +1,47 @@ use { askama::Template, axum::{extract::State, routing::get, Router}, - std::env, + thiserror::Error, tower_http::services::ServeDir, }; +mod config; mod db; + +use config::get_config; use db::Database; -#[tokio::main] -async fn main() -> Result<(), Box> { - let db_pool = Database::create_pool(&env::var("LOCALHUB_DATABASE_URL")?, 2)?; +#[derive(Error, Debug)] +pub enum Error { + #[error("Loading configuration: \"{0}\"")] + MissingConfigError(#[from] config::Error), + + #[error("Database error: {0}")] + DatabaseError(#[from] db::Error), + + #[error("{0}")] + IOError(#[from] std::io::Error), +} + +fn main() { + let runtime = tokio::runtime::Runtime::new().unwrap(); + std::process::exit(match runtime.block_on(localhub_main()) { + Ok(()) => 0, + Err(err) => { + eprintln!("ERROR: {}", err); + 1}, + }) +} + +async fn localhub_main() -> Result<(), Error> { + let config = get_config()?; + + let db_pool = Database::create_pool(&config.database_url, 2)?; let app = Router::new() .route("/", get(root)) .with_state(db_pool) - .nest_service( - "/static", - ServeDir::new(env::var("LOCALHUB_STATIC_FILE_PATH")?), - ); + .nest_service("/static", ServeDir::new(&config.static_file_path)); let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await?; axum::serve(listener, app).await?;