Skip to main content

br_web_server/
config.rs

1use json::{object, JsonValue};
2use serde::{Deserialize, Serialize};
3use std::fs;
4use std::path::{Path, PathBuf};
5
6#[derive(Debug, Clone, Deserialize, Serialize)]
7pub struct Config {
8    /// 调试
9    pub debug: bool,
10    /// 主机
11    pub host: String,
12    /// SSL/TLS
13    pub https: bool,
14    pub tls: TlsConfig,
15    /// 日志记录
16    pub log: bool,
17    /// 运行根目录
18    pub root_path: PathBuf,
19    /// 公开目录
20    pub public: String,
21    /// 网页目录
22    pub webpage: String,
23    /// 运行时目录
24    pub runtime: String,
25    /// 语言
26    pub charset: String,
27    /// 密钥token
28    pub token: String,
29    /// 密钥文件路径
30    pub pub_key_path: String,
31    /// 最大请求体大小 (字节),默认 10MB
32    #[serde(default = "default_max_body_size")]
33    pub max_body_size: usize,
34    /// 读取超时 (秒)
35    #[serde(default = "default_read_timeout")]
36    pub read_timeout: u64,
37    /// 写入超时 (秒)
38    #[serde(default = "default_write_timeout")]
39    pub write_timeout: u64,
40}
41
42fn default_max_body_size() -> usize {
43    10 * 1024 * 1024
44}
45
46fn default_read_timeout() -> u64 {
47    30
48}
49
50fn default_write_timeout() -> u64 {
51    30
52}
53impl Config {
54    #[must_use]
55    pub fn default(path: PathBuf) -> Self {
56        Self {
57            debug: true,
58            host: "0.0.0.0:3535".to_string(),
59            https: false,
60            tls: TlsConfig::new(),
61            log: true,
62            root_path: path,
63            public: "public".to_string(),
64            webpage: "spa".to_string(),
65            runtime: "runtime".to_string(),
66            charset: "utf-8".to_string(),
67            token: String::new(),
68            pub_key_path: String::new(),
69            max_body_size: default_max_body_size(),
70            read_timeout: default_read_timeout(),
71            write_timeout: default_write_timeout(),
72        }
73    }
74
75    #[must_use]
76    pub fn create(config_file: &Path, pkg_name: bool) -> Config {
77        let dir = config_file.parent().unwrap().to_path_buf();
78        #[derive(Clone, Debug, Deserialize, Serialize)]
79        pub struct ConfigPkg {
80            pub br_web_server: Config,
81        }
82        impl ConfigPkg {
83            pub fn new(dir: PathBuf) -> ConfigPkg {
84                Self {
85                    br_web_server: Config::default(dir),
86                }
87            }
88        }
89        let mut data = Config::default(dir.clone());
90        data.from();
91        match fs::read_to_string(config_file) {
92            Ok(e) => {
93                if pkg_name {
94                    toml::from_str::<ConfigPkg>(&e).unwrap().br_web_server
95                } else {
96                    data
97                }
98            }
99            Err(_) => {
100                if pkg_name {
101                    let data = ConfigPkg::new(dir);
102                    fs::create_dir_all(config_file.parent().unwrap()).unwrap();
103                    let toml = toml::to_string(&data).unwrap();
104                    let _ = fs::write(config_file.to_str().unwrap(), toml);
105                    data.br_web_server
106                } else {
107                    let data = Config::default(dir);
108                    fs::create_dir_all(config_file.parent().unwrap()).unwrap();
109                    let toml = toml::to_string(&data).unwrap();
110                    let _ = fs::write(config_file.to_str().unwrap(), toml);
111                    data
112                }
113            }
114        }
115    }
116    fn from(&mut self) -> &mut Config {
117        let root = self.root_path.clone();
118        let runtime = root
119            .join(self.runtime.clone())
120            .to_str()
121            .unwrap()
122            .to_string();
123        let public = root.join(self.public.clone()).to_str().unwrap().to_string();
124        let webpage = root.join("webpage").to_str().unwrap().to_string();
125        let ssl = root.join("ssl").to_str().unwrap().to_string();
126
127        fs::create_dir_all(ssl.clone()).unwrap();
128        fs::create_dir_all(runtime.clone()).unwrap();
129        fs::create_dir_all(public.clone()).unwrap();
130        fs::create_dir_all(webpage.clone()).unwrap();
131
132        self
133    }
134    #[must_use]
135    pub fn json(self) -> JsonValue {
136        object! {
137            debug: self.debug,
138            log: self.log,
139            host: self.host,
140            https: self.https,
141            root_path:self.root_path.to_str().unwrap(),
142            public: self.public,
143            webpage: self.webpage,
144            runtime: self.runtime,
145            charset: self.charset,
146            token: self.token,
147            pub_key_path: self.pub_key_path,
148            max_body_size: self.max_body_size,
149            read_timeout: self.read_timeout,
150            write_timeout: self.write_timeout,
151        }
152    }
153}
154
155#[derive(Clone, Debug, Deserialize, Serialize)]
156pub struct TlsConfig {
157    pub certs: PathBuf,
158    pub key: PathBuf,
159}
160impl TlsConfig {
161    fn new() -> Self {
162        Self {
163            certs: PathBuf::default(),
164            key: PathBuf::default(),
165        }
166    }
167    pub fn json(&mut self) -> JsonValue {
168        object! {
169            certs:self.certs.to_str().unwrap_or(""),
170            key: self.key.to_str().unwrap_or(""),
171        }
172    }
173    #[must_use]
174    pub fn from(value: &JsonValue, root: &Path) -> Self {
175        Self {
176            certs: root.join(value["certs"].as_str().unwrap_or("")),
177            key: root.join(value["key"].as_str().unwrap_or("")),
178        }
179    }
180}