daoyi_cloud_common/config/
mod.rs1use std::sync::OnceLock;
2
3pub use figment::Figment;
4pub use figment::providers::Data;
5pub use figment::providers::{Env, Format, Toml};
6use serde::Deserialize;
7use tracing::{error, info};
8
9mod log_config;
10pub use log_config::LogConfig;
11mod db_config;
12mod redis_config;
13
14pub use db_config::DbConfig;
15pub use redis_config::RedisConfig;
16
17pub static CONFIG: OnceLock<ServerConfig> = OnceLock::new();
18
19pub fn common_init(init_toml: Option<Data<Toml>>) {
20 let data = Toml::file(Env::var("APP_CONFIG").as_deref().unwrap_or("config.toml"));
21 let data2 = Toml::file(Env::var("APP_CONFIG").as_deref().unwrap_or("config.toml"));
22 let raw_config = Figment::new()
23 .merge(data)
24 .merge(Env::prefixed("APP_").global())
25 .merge(init_toml.unwrap_or(data2));
26 let mut config = match raw_config.extract::<ServerConfig>() {
27 Ok(s) => s,
28 Err(e) => {
29 eprintln!("It looks like your config is invalid. The following error occurred: {e}");
30 std::process::exit(1);
31 }
32 };
33 let _guard = config.log.guard();
34 info!("log level: {}", &config.log.filter_level);
35 if config.db.url.is_empty() {
36 config.db.url = std::env::var("DATABASE_URL").unwrap_or_default();
37 }
38 if config.db.url.is_empty() {
39 error!("DATABASE_URL is not set");
40 std::process::exit(1);
41 }
42 CONFIG.set(config).expect("config should be set");
43 info!("Config loaded: {:#?}", CONFIG.get().unwrap());
44}
45pub fn get() -> &'static ServerConfig {
46 CONFIG.get().expect("config should be set")
47}
48
49#[derive(Deserialize, Clone, Debug)]
50pub struct ProfileActiveConfig {
51 #[serde(default = "default_profile_active")]
52 pub profile_active: String,
53}
54
55#[derive(Deserialize, Clone, Debug)]
56pub struct ServerConfig {
57 #[serde(default = "default_listen_addr")]
58 pub listen_addr: String,
59
60 pub db: DbConfig,
61 pub log: LogConfig,
62 pub jwt: JwtConfig,
63 pub tls: Option<TlsConfig>,
64 pub redis: RedisConfig,
65}
66
67#[derive(Deserialize, Clone, Debug)]
68pub struct JwtConfig {
69 pub secret: String,
70 pub expiry: i64,
71}
72#[derive(Deserialize, Clone, Debug)]
73pub struct TlsConfig {
74 pub cert: String,
75 pub key: String,
76}
77
78#[allow(dead_code)]
79pub fn default_false() -> bool {
80 false
81}
82#[allow(dead_code)]
83pub fn default_true() -> bool {
84 true
85}
86
87fn default_listen_addr() -> String {
88 "127.0.0.1:8008".into()
89}
90
91fn default_profile_active() -> String {
92 "test".into()
93}