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