aux_config/
lib.rs

1use std::env;
2
3use config::Config;
4use lazy_static::lazy_static;
5
6lazy_static! {
7    /// 加载配置文件。通过环境变量 config_dir 指定配置文件路径,默认 conf。通过环境变量 profile 指定配置文件。
8    /// 配置文件格式:application_{profile}.[yaml|json|toml]
9    ///
10    /// # Example
11    ///
12    /// ```
13    /// use aux_svc::APP_CONFIG;
14    /// println!("{}", APP_CONFIG.get_str("mysql.url").unwrap());
15    /// ```
16    pub static ref APP_CONFIG: Config = {
17        let mut _config = Config::new();
18        let config_dir = env::var("config_dir").unwrap_or("conf".to_string());
19        _config.merge(config::File::with_name(&format!("{}/application", config_dir))).unwrap();
20
21        if let Ok(profile) = env::var("profile") {
22            let config_file_name = format!("{}/application_{}", config_dir, profile);
23            _config.merge(config::File::with_name(&config_file_name)).unwrap();
24        }
25
26        _config
27    };
28}
29
30/// 用于定义配置项
31///
32/// # Example
33///
34/// ```
35/// aux_svc::config_keys! {
36///     (MYSQL_URL, "mysql.url");
37/// }
38/// println!("{}", ConfigKey::MYSQL_URL);
39/// ```
40#[macro_export] macro_rules! config_keys {
41    (
42        $(
43            $(#[$docs:meta])*
44            $vis:vis $struct_name:ident {
45                $(($name:ident, $key:expr);)+
46            }
47        )+
48    ) => {
49        $(
50            $(#[$docs])*
51            $vis struct $struct_name;
52
53            impl $struct_name {
54                $(pub const $name: &'static str = $key;)+
55            }
56        )+
57    }
58}