Streamlined config usage

This commit is contained in:
mtrx 2024-05-15 00:36:14 +02:00
parent 9be7442f7d
commit 35cd018152
6 changed files with 234 additions and 247 deletions

View file

@ -1,6 +1,7 @@
mod api;
mod db;
mod routes;
mod config;
#[macro_use]
extern crate diesel;
@ -10,76 +11,18 @@ extern crate tera;
use actix_files as fs;
use actix_web::{middleware::Logger, web::Data, App, HttpServer};
use std::env;
use env_logger::Env;
use once_cell::sync::Lazy;
use std::{collections::HashMap, env, sync::RwLock};
use tera::Tera;
pub static CONFIG_MAP: Lazy<RwLock<HashMap<String, String>>> = Lazy::new(|| {
let mut config: HashMap<String, String> = HashMap::new();
let required_env_vars = [
"SUBMIT_TOKEN",
"ROOT_PATH",
"USERNAME",
"EMAIL",
"BIND_PORT",
];
let optional_env_vars = [
"GITHUB_ACCOUNT",
"TWITTER_ACCOUNT",
"MASTODON_ACCOUNT",
"DISCORD_ACCOUNT",
"REDDIT_ACCOUNT",
];
// Test if variable is set. If not, panic.
let mut insert_required_env = |env: &str| {
let env_string = String::from(env);
config.insert(
env_string.clone(), // env var name
env::var(env_string).expect(format!("`{}` variable not set.", env).as_str()), // env var content
)
};
for var in required_env_vars.iter() {
insert_required_env(var);
}
// Test if variable is set. If it is insert into config.
let mut insert_optional_env = |env: &str| {
if let Ok(var_content) = env::var(String::from(env)) {
config.insert(String::from(env), var_content.clone());
}
};
for var in optional_env_vars.iter() {
insert_optional_env(var);
}
// Print some info about the current configuration
println!("Submit token = `{}`", config.get("SUBMIT_TOKEN").unwrap());
println!(
"Current working directory = `{}`",
env::current_dir().unwrap().to_str().unwrap()
);
println!("Root path = `{}`", config.get("ROOT_PATH").unwrap());
println!(
"Template path = `{}/templates/*`",
config.get("ROOT_PATH").unwrap()
);
println!("Launching on 0.0.0.0:{}", config.get("BIND_PORT").unwrap());
RwLock::new(config)
});
use config::CONFIG;
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
HttpServer::new(move || {
let mut tera = Tera::new(
format!(
"{}{}",
CONFIG_MAP.read().unwrap().get("ROOT_PATH").unwrap(),
env::var("ROOT_PATH").unwrap(),
"/templates/*"
)
.as_str(),
@ -107,16 +50,13 @@ async fn main() -> std::io::Result<()> {
"/static",
format!(
"{}{}",
CONFIG_MAP.read().unwrap().get("ROOT_PATH").unwrap(),
CONFIG.root_path,
"/static"
),
))
.wrap(Logger::new("%a %r %t"))
})
.bind(format!(
"0.0.0.0:{}",
CONFIG_MAP.read().unwrap().get("BIND_PORT").unwrap()
))?
.bind(format!("0.0.0.0:{}", CONFIG.bind_port))?
.run()
.await
}