diff --git a/.env b/.env index 845d1db..bd70fbd 100644 --- a/.env +++ b/.env @@ -1,7 +1,5 @@ -WEB.ADDR=0.0.0.0:9527 - -MYSQL.MAX_CONS=5 -MYSQL.DSN=mysql://root:mysql123!%40%23@127.0.0.1:3306/study - # 日志级别 RUST_LOG=DEBUG + +# 运行模式 +RUN_MODE=dev diff --git a/config/default.toml b/config/default.toml new file mode 100644 index 0000000..7f08d84 --- /dev/null +++ b/config/default.toml @@ -0,0 +1,6 @@ +[web] +addr = "0.0.0.0:9527" + +[mysql] +max_cons = 5 +dsn = "mysql://root:mysql123!%40%23@127.0.0.1:3306/study" diff --git a/src/config/default.toml b/config/dev.toml similarity index 100% rename from src/config/default.toml rename to config/dev.toml diff --git a/src/config.rs b/src/config.rs index 7eed089..81f83ea 100644 --- a/src/config.rs +++ b/src/config.rs @@ -1,3 +1,5 @@ +use std::env; +use config::File; use serde::Deserialize; use crate::{err::Error, Result}; @@ -21,9 +23,19 @@ pub struct AppConfig { } impl AppConfig { - pub fn from_env() -> Result { + pub fn new() -> Result { + let run_mode = env::var("RUN_MODE").unwrap_or_else(|_| "dev".into()); + + // https://github.com/mehcode/config-rs/blob/master/examples/hierarchical-env/settings.rs config::Config::builder() - .add_source(config::Environment::default()) + // Start off by merging in the "default" configuration file + .add_source(File::with_name("config/default")) + // Add in the current environment file + // Default to 'dev' env + // Note that this file is _optional_ + .add_source( + File::with_name(&format!("config/{}", run_mode)).required(false), + ) .build() .map_err(Error::from)? .try_deserialize() diff --git a/src/main.rs b/src/main.rs index ba5ab67..6ae74fe 100644 --- a/src/main.rs +++ b/src/main.rs @@ -15,7 +15,7 @@ async fn main() { tracing_subscriber::fmt::init(); - let cfg = AppConfig::from_env() + let cfg = AppConfig::new() .map_err(|e| tracing::error!("初始化配置失败:{}", e.to_string())) .unwrap();