1use json::JsonValue;
2
3#[derive(Clone, Debug)]
4pub struct Config {
5 pub debug: bool,
7 pub username: String,
9 pub userpass: String,
11 pub database: String,
13 pub hostname: String,
15 pub hostport: i32,
17 pub charset: String,
19 pub pool_max: u32,
21}
22
23impl Config {
24 pub fn new(config: &JsonValue) -> Config {
25 let hostport = config["hostport"].as_i32().unwrap_or(5432);
26 let hostport = if (1..=65535).contains(&hostport) {
27 hostport
28 } else {
29 5432
30 };
31 let sanitize = |s: &str| -> String { s.replace('\0', "") };
32 Self {
33 debug: config["debug"].as_bool().unwrap_or(false),
34 username: sanitize(config["username"].as_str().unwrap_or("postgres")),
35 userpass: sanitize(config["userpass"].as_str().unwrap_or("111111")),
36 database: sanitize(config["database"].as_str().unwrap_or("postgres")),
37 hostname: sanitize(config["hostname"].as_str().unwrap_or("localhost")),
38 hostport,
39 charset: sanitize(config["charset"].as_str().unwrap_or("utf8mb4")),
40 pool_max: config["pool_max"].as_u32().unwrap_or(5),
41 }
42 }
43 pub fn url(&mut self) -> String {
44 format!("{}:{}", self.hostname, self.hostport)
45 }
46}
47
48#[cfg(test)]
49mod tests {
50 use super::*;
51
52 #[test]
53 fn hostport_out_of_range_falls_back_to_default() {
54 let cfg = Config::new(&json::object! { "hostport": 99999 });
55 assert_eq!(cfg.hostport, 5432);
56 }
57
58 #[test]
59 fn hostport_zero_falls_back_to_default() {
60 let cfg = Config::new(&json::object! { "hostport": 0 });
61 assert_eq!(cfg.hostport, 5432);
62 }
63
64 #[test]
65 fn hostport_negative_falls_back_to_default() {
66 let cfg = Config::new(&json::object! { "hostport": -1 });
67 assert_eq!(cfg.hostport, 5432);
68 }
69
70 #[test]
71 fn hostport_valid_is_kept() {
72 let cfg = Config::new(&json::object! { "hostport": 5433 });
73 assert_eq!(cfg.hostport, 5433);
74 }
75}