根据不同开发环境读取不同配置文件
This commit is contained in:
parent
061de4a1ee
commit
de82c83a2a
8
.env
8
.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
|
||||
|
|
|
@ -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"
|
|
@ -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<Self> {
|
||||
pub fn new() -> Result<Self> {
|
||||
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()
|
||||
|
|
|
@ -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();
|
||||
|
||||
|
|
Loading…
Reference in New Issue