1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
use serde::{Deserialize, Serialize};

/// Configuration object for WICRS Server.
#[derive(Serialize, Deserialize, Clone)]
pub struct Config {
    /// Base URL of the PGP key server to use.
    pub key_server: String,
    /// Address to listen on for HTTP requests. (`host:port`)
    pub address: String,
    /// Whether or not to show the version of WICRS server on the root webpage (`http(s)://host:port/`)
    pub show_version: bool,
    /// ID to give the generated PGP KeyPair.
    pub key_id: Option<String>,
}

impl Default for Config {
    fn default() -> Self {
        Self {
            key_server: "https://keys.openpgp.org".to_string(),
            address: "127.0.0.1:8080".to_string(),
            show_version: true,
            key_id: None,
        }
    }
}

/// Loads the configuration for wicrs_server from `./config.json`. Causes exit with code 1 if the file cannot be found or cannot be deserialized.
pub fn load_config(path: &str) -> Config {
    if let Ok(read) = std::fs::read_to_string(path) {
        if let Ok(config) = serde_json::from_str::<Config>(&read) {
            return config;
        } else {
            warn!(
                "{} does not contain a valid configuration, using defaults...",
                path
            );
        }
    } else {
        warn!("Failed to read {}, using defaults...", path);
    }
    let config = Config::default();
    if std::fs::write(path, &serde_json::to_string_pretty(&config).unwrap()).is_ok() {
        error!("Failed to write default config to {}", path);
    }
    config
}