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
use std::{env, fs, path::PathBuf, sync::Arc};
use serde::{Deserialize, Serialize};
use toml::{
self,
value::{Map, Value},
};
use viz_utils::{futures::future::BoxFuture, tracing};
use crate::{Context, Error, Extract, Result};
use super::{Cookies, Env, Limits};
#[derive(Debug, Deserialize, Serialize)]
pub struct Config {
#[serde(skip_deserializing)]
pub env: Env,
#[serde(default)]
pub limits: Limits,
#[serde(default)]
pub cookies: Cookies,
#[serde(default)]
pub extras: Map<String, Value>,
pub dir: PathBuf,
}
impl Config {
pub async fn load() -> Result<Config> {
let path = env::current_dir()?;
let e = Env::get();
let config_path = path.join("config").join(e.to_string() + ".toml");
let mut config = if config_path.exists() {
toml::from_str(&fs::read_to_string(config_path)?).unwrap_or_default()
} else {
Config::default()
};
config.dir = path;
config.env = e;
tracing::info!("{:#?}", config);
Ok(config)
}
}
impl Default for Config {
fn default() -> Self {
Self {
limits: Limits::default(),
cookies: Cookies::default(),
env: Env::default(),
extras: Map::default(),
dir: env::current_dir().unwrap_or_default(),
}
}
}
impl Config {
pub fn new() -> Self {
Self::default()
}
}
impl Extract for Arc<Config> {
type Error = Error;
#[inline]
fn extract<'a>(cx: &'a mut Context) -> BoxFuture<'a, Result<Self, Self::Error>> {
Box::pin(async move { Ok(cx.config()) })
}
}
impl Context {
pub fn config(&self) -> Arc<Config> {
self.extensions().get::<Arc<Config>>().cloned().unwrap_or_default()
}
}