hehe_server/
config.rs

1use serde::{Deserialize, Serialize};
2use std::net::SocketAddr;
3
4#[derive(Clone, Debug, Serialize, Deserialize)]
5pub struct ServerConfig {
6    #[serde(default = "default_host")]
7    pub host: String,
8
9    #[serde(default = "default_port")]
10    pub port: u16,
11
12    #[serde(default)]
13    pub cors_origins: Vec<String>,
14
15    #[serde(default = "default_max_connections")]
16    pub max_connections: usize,
17}
18
19fn default_host() -> String {
20    "0.0.0.0".to_string()
21}
22
23fn default_port() -> u16 {
24    3000
25}
26
27fn default_max_connections() -> usize {
28    1000
29}
30
31impl Default for ServerConfig {
32    fn default() -> Self {
33        Self {
34            host: default_host(),
35            port: default_port(),
36            cors_origins: vec![],
37            max_connections: default_max_connections(),
38        }
39    }
40}
41
42impl ServerConfig {
43    pub fn new() -> Self {
44        Self::default()
45    }
46
47    pub fn with_host(mut self, host: impl Into<String>) -> Self {
48        self.host = host.into();
49        self
50    }
51
52    pub fn with_port(mut self, port: u16) -> Self {
53        self.port = port;
54        self
55    }
56
57    pub fn with_cors_origin(mut self, origin: impl Into<String>) -> Self {
58        self.cors_origins.push(origin.into());
59        self
60    }
61
62    pub fn socket_addr(&self) -> SocketAddr {
63        format!("{}:{}", self.host, self.port)
64            .parse()
65            .expect("Invalid socket address")
66    }
67}
68
69#[cfg(test)]
70mod tests {
71    use super::*;
72
73    #[test]
74    fn test_config_default() {
75        let config = ServerConfig::default();
76        assert_eq!(config.host, "0.0.0.0");
77        assert_eq!(config.port, 3000);
78    }
79
80    #[test]
81    fn test_config_builder() {
82        let config = ServerConfig::new()
83            .with_host("127.0.0.1")
84            .with_port(8080)
85            .with_cors_origin("http://localhost:3000");
86
87        assert_eq!(config.host, "127.0.0.1");
88        assert_eq!(config.port, 8080);
89        assert_eq!(config.cors_origins.len(), 1);
90    }
91
92    #[test]
93    fn test_socket_addr() {
94        let config = ServerConfig::new().with_host("127.0.0.1").with_port(8080);
95        let addr = config.socket_addr();
96        assert_eq!(addr.to_string(), "127.0.0.1:8080");
97    }
98}