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
|
use std::env;
use std::net::SocketAddr;
use std::str::FromStr;
#[derive(Clone)]
pub struct Config {
pub auth_secret: String,
pub db_path: String,
pub mock_mails: bool,
pub secure_cookies: bool,
pub socket_address: SocketAddr,
}
pub fn from_env() -> Result<Config, String> {
Ok(Config {
auth_secret: read_string("AUTH_SECRET")?,
db_path: read_string("DB_PATH")?,
mock_mails: read_bool("MOCK_MAILS")?,
secure_cookies: read_bool("SECURE_COOKIES")?,
socket_address: read_socket_address("SOCKET_ADDRESS")?,
})
}
fn read_socket_address(key: &str) -> Result<SocketAddr, String> {
SocketAddr::from_str(&read_string(key)?).map_err(|err| {
format!("environment variable '{key}' is not a socket address: {err}")
})
}
fn read_bool(key: &str) -> Result<bool, String> {
read_string(key).and_then(|v| match v.as_str() {
"true" => Ok(true),
"false" => Ok(false),
_ => Err(format!(
"environment variable '{key}' is not a boolean: '{v}'"
)),
})
}
fn read_string(key: &str) -> Result<String, String> {
env::var(key).map_err(|_| format!("missing environment variable '{key}'"))
}
|