config.rs 1.22 KB
use std::fs::File;
use std::io::Read;
use once_cell::sync::Lazy;
use serde::Deserialize;

#[derive(Debug, Deserialize)]
struct Database { url :Option<String> }

#[derive(Debug, Deserialize)]
struct Locations { upload :String
                 , images :String }

#[derive(Debug, Deserialize)]
pub(crate) struct Config { namespace :String
                         , database  :Database
                         , locations :Locations }

pub(crate) static CONFIG :Lazy<Config> = Lazy::new(|| Config::load());

impl Config {
    pub fn load() -> Config {
        let filename = std::env::var("CONFIG").unwrap();

        let mut buffer = vec![];
        let mut file = File::open(filename).unwrap();

        file.read_to_end(&mut buffer).unwrap();
        let mut config :Config = toml::from_slice(&buffer).unwrap();

        config.database.url = match config.database.url {
            Some(url) => Some(url),
            None => std::env::var("DATABASE_URL").ok()
        };

        config
    }

    pub fn namespace(&self) -> &str {
        self.namespace.as_str()
    }

    pub fn upload_dir(&self) -> &str {
        self.locations.upload.as_str()
    }

    pub fn images_dir(&self) -> &str {
        self.locations.images.as_str()
    }
}