use std::error::Error; use yaml_rust::{Yaml, YamlLoader}; /// Server configuration /// /// @author Pierre Hubert #[derive(Debug)] pub struct DatabaseConfig { pub host: String, pub name: String, pub username: String, pub password: String, pub log_all_queries: bool, } #[derive(Debug)] pub struct Config { pub port: i32, pub listen_address: String, pub storage_url: String, pub storage_path: String, pub database: DatabaseConfig, pub proxy: Option, pub force_https: bool, } /// Globally available configuration static mut CONF: Option = None; impl Config { fn yaml_i32(parsed: &Yaml, name: &str) -> i32 { parsed[name].as_i64().expect(format!("{} is missing (int)", name).as_str()) as i32 } fn yaml_str(parsed: &Yaml, name: &str) -> String { parsed[name].as_str().expect(format!("{} is missing (str)", name).as_str()).to_string() } fn yaml_bool(parsed: &Yaml, name: &str) -> bool { parsed[name].as_bool().expect(format!("{} is missing (bool)", name).as_str()) } /// Load the configuration from a given path pub fn load(path: &str) -> Result<(), Box> { // Read & parse configuration let conf_str = std::fs::read_to_string(path)?; let parsed = YamlLoader::load_from_str(&conf_str)?; if parsed.len() != 1 { panic!("parsed.len() != 1"); } let parsed = &parsed[0]; // Read configuration let parsed_db = &parsed["database"]; let database_conf = DatabaseConfig { host: Config::yaml_str(parsed_db, "host"), name: Config::yaml_str(parsed_db, "name"), username: Config::yaml_str(parsed_db, "username"), password: Config::yaml_str(parsed_db, "password"), log_all_queries: Config::yaml_bool(parsed_db, "log_all_queries"), }; let proxy = Config::yaml_str(parsed, "proxy"); let conf = Config { port: Config::yaml_i32(parsed, "server-port") as i32, listen_address: Config::yaml_str(parsed, "server-address"), storage_url: Config::yaml_str(parsed, "storage-url"), storage_path: Config::yaml_str(parsed, "storage-path"), database: database_conf, proxy: match proxy.as_ref() { "none" => None, s => Some(s.to_string()) }, force_https: Config::yaml_bool(parsed, "force-https"), }; // Save new configuration in memory unsafe { CONF = Some(conf); } Ok(()) } /// Get the address this server listen to pub fn server_listen_address(&self) -> String { format!("{}:{}", self.listen_address, self.port) } } /// Get an instance of the configuration pub fn conf() -> &'static Config { unsafe { return &CONF.as_ref().unwrap(); } }