tin_config_load/
config.rs1pub struct ConfigLoader {
2 builder: config::ConfigBuilder<config::builder::DefaultState>,
3 path: String,
4}
5
6impl Default for ConfigLoader {
7 fn default() -> Self {
8 Self {
9 builder: config::Config::builder()
10 .add_source(config::File::with_name("./config/default").required(false))
11 .add_source(config::Environment::with_prefix("APP")),
12 path: String::from("./config/default"),
13 }
14 }
15}
16
17impl ConfigLoader {
18 pub fn file(mut self, path: &str) -> Self {
20 self.path = path.to_string();
21 self.builder = self.builder.add_source(config::File::with_name(&self.path));
22 self
23 }
24
25 pub fn env(mut self, prefix: &str) -> Self {
27 self.builder = self
28 .builder
29 .add_source(config::Environment::with_prefix(prefix));
30 self
31 }
32
33 pub fn default_file(mut self) -> Self {
35 self.builder = self
36 .builder
37 .add_source(config::File::with_name("./config/default").required(false));
38 self
39 }
40
41 pub fn default_env(mut self) -> Self {
43 self.builder = self
44 .builder
45 .add_source(config::Environment::with_prefix("APP"));
46 self
47 }
48
49 pub fn build<T: serde::de::DeserializeOwned>(self) -> Result<T, config::ConfigError> {
51 let s = self.builder.build()?;
52 match s.try_deserialize() {
53 Ok(cfg) => Ok(cfg),
54 Err(e) => {
55 log::error!("配置反序列化失败: {e}");
56 Err(e)
57 }
58 }
59 }
60}