akv/
config.rs

1use std::error::Error;
2
3use serde::{Deserialize, Serialize};
4
5use crate::utils::resolve_config_path;
6
7#[derive(Deserialize, Serialize, Clone)]
8pub struct Config {
9    #[serde(default = "default_host")]
10    pub host: String,
11
12    #[serde(default = "default_port")]
13    pub port: u16,
14
15    #[serde(default = "default_string")]
16    pub secret: String,
17}
18
19fn default_host() -> String {
20    "0.0.0.0".into()
21}
22fn default_port() -> u16 {
23    60002
24}
25
26fn default_string() -> String {
27    "".into()
28}
29
30impl Config {
31    pub fn new(config_path: Option<&str>) -> Result<Self, Box<dyn Error>> {
32        let config_file = config_path.unwrap_or("./config.toml");
33
34        match resolve_config_path(config_file) {
35            Ok(abs_path) => {
36                if !abs_path.exists() || !abs_path.is_file() {
37                    Ok(Self::default())
38                } else {
39                    let content = std::fs::read_to_string(abs_path)?;
40                    let mut config = toml::from_str::<Config>(&content)?;
41                    config.parse_env_var();
42                    Ok(config)
43                }
44            }
45            Err(e) => {
46                panic!("Failed to resolve config file path: {}", e);
47            }
48        }
49    }
50
51    pub fn parse_env_var(&mut self) {
52        if let Ok(host) = std::env::var("AKV_HOST") {
53            self.host = host;
54        }
55        if let Ok(port) = std::env::var("AKV_PORT") {
56            self.port = port.parse().unwrap();
57        }
58    }
59
60    pub fn get_address(&self) -> String {
61        format!("{}:{}", self.host, self.port)
62    }
63}
64
65impl Default for Config {
66    fn default() -> Self {
67        Self {
68            host: default_host(),
69            port: default_port(),
70            secret: default_string(),
71        }
72    }
73}