1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
pub use components::*;
pub use standard::*;
pub use utils::*;
mod standard;
pub trait Configurable {
type Config;
fn configure(config: Self::Config) -> Result<Self::Config, config::ConfigError>;
}
#[derive(Clone, Debug, Hash, PartialEq, serde::Deserialize, serde::Serialize)]
pub struct Configuration {
pub application: AppParams,
pub database: DatabaseParams,
pub logger: LoggerParams,
pub server: ServerParams,
}
impl Configuration {
pub fn new() -> Result<Self, config::ConfigError> {
let mut builder = construct_config_builder();
builder = builder
.set_default("application.mode", "dev")?
.set_default("application.name", "acme")?
.set_default("logger.level", "info")?;
builder = collect_config_files(builder, "**/*.config.*", false);
builder.build()?.try_deserialize()
}
}
impl std::fmt::Display for Configuration {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"Settings(application={}, logger={})",
self.application, self.logger
)
}
}
mod components {
#[derive(Clone, Debug, Hash, PartialEq, serde::Deserialize, serde::Serialize)]
pub struct AppParams {
pub mode: String,
pub name: String,
}
impl AppParams {
fn constructor(mode: String, name: String) -> Self {
Self { mode, name }
}
pub fn new(mode: String, name: String) -> Self {
Self::constructor(mode, name)
}
pub fn from(mode: &str, name: &str) -> Self {
Self::constructor(String::from(mode), String::from(name))
}
}
impl std::fmt::Display for AppParams {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Application(mode={}, name={})", self.mode, self.name)
}
}
#[derive(Clone, Debug, Hash, PartialEq, serde::Deserialize, serde::Serialize)]
pub struct DatabaseParams {
pub name: String,
pub uri: String,
}
impl std::fmt::Display for DatabaseParams {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Database(name={}, uri={})", self.name, self.uri)
}
}
#[derive(Clone, Debug, Hash, PartialEq, serde::Deserialize, serde::Serialize)]
pub struct LoggerParams {
pub level: String,
}
impl LoggerParams {
fn constructor(level: String) -> Self {
Self { level }
}
pub fn setup(config: &crate::Configuration) -> Self {
if std::env::var_os("RUST_LOG").is_none() {
let app_name = config.application.name.as_str();
let level = config.logger.level.as_str();
let env = format!("api={},tower_http={}", app_name, level);
std::env::set_var("RUST_LOG", env);
}
tracing_subscriber::fmt::init();
Self::constructor(config.logger.level.clone())
}
}
impl std::fmt::Display for LoggerParams {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Logger(level={})", self.level)
}
}
#[derive(Clone, Debug, Hash, PartialEq, serde::Deserialize, serde::Serialize)]
pub struct ServerParams {
pub port: u16,
pub host: String,
}
impl std::fmt::Display for ServerParams {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Server(port={})", self.port)
}
}
}
mod utils {
use crate::ConfigBuilderDS;
pub fn construct_config_builder() -> ConfigBuilderDS {
config::Config::builder()
}
pub fn collect_config_files(
builder: ConfigBuilderDS,
pattern: &str,
required: bool,
) -> ConfigBuilderDS {
builder.add_source(
glob::glob(pattern)
.unwrap()
.map(|path| config::File::from(path.unwrap()).required(required))
.collect::<Vec<_>>(),
)
}
pub fn collect_host_from_string<T>(string: String, breakpoint: char) -> Vec<T>
where
T: Clone + std::str::FromStr,
<T as std::str::FromStr>::Err: std::fmt::Debug,
{
let exclude: &[char] = &[' ', ',', '[', ']', '.'];
let trimmed: &str = &string.trim_matches(exclude);
trimmed
.split(breakpoint)
.map(|i| i.trim_matches(exclude).parse::<T>().unwrap())
.collect()
}
}