1use serde::{Deserialize, Serialize};
9use std::net::SocketAddr;
10
11#[derive(Debug, Clone, Serialize, Deserialize)]
17pub struct ServerConfig {
18 pub host: String,
19 pub port: u16,
20 pub max_connections: usize,
21 pub request_timeout_secs: u64,
22 pub body_limit_bytes: usize,
23 pub enable_cors: bool,
24 pub tls: Option<TlsConfig>,
25}
26
27impl Default for ServerConfig {
28 fn default() -> Self {
29 Self {
30 host: "127.0.0.1".to_string(),
31 port: 3000,
32 max_connections: 10000,
33 request_timeout_secs: 30,
34 body_limit_bytes: 10 * 1024 * 1024, enable_cors: true,
36 tls: None,
37 }
38 }
39}
40
41impl ServerConfig {
42 pub fn new(host: &str, port: u16) -> Self {
44 Self {
45 host: host.to_string(),
46 port,
47 ..Default::default()
48 }
49 }
50
51 pub fn socket_addr(&self) -> SocketAddr {
53 format!("{}:{}", self.host, self.port)
54 .parse()
55 .unwrap_or_else(|_| SocketAddr::from(([127, 0, 0, 1], self.port)))
56 }
57
58 pub fn with_tls(mut self, cert_path: &str, key_path: &str) -> Self {
60 self.tls = Some(TlsConfig {
61 cert_path: cert_path.to_string(),
62 key_path: key_path.to_string(),
63 });
64 self
65 }
66
67 pub fn with_max_connections(mut self, max: usize) -> Self {
69 self.max_connections = max;
70 self
71 }
72
73 pub fn with_timeout(mut self, secs: u64) -> Self {
75 self.request_timeout_secs = secs;
76 self
77 }
78}
79
80#[derive(Debug, Clone, Serialize, Deserialize)]
86pub struct TlsConfig {
87 pub cert_path: String,
88 pub key_path: String,
89}
90
91#[cfg(test)]
96mod tests {
97 use super::*;
98
99 #[test]
100 fn test_default_config() {
101 let config = ServerConfig::default();
102 assert_eq!(config.host, "127.0.0.1");
103 assert_eq!(config.port, 3000);
104 assert!(config.tls.is_none());
105 }
106
107 #[test]
108 fn test_socket_addr() {
109 let config = ServerConfig::new("0.0.0.0", 8080);
110 let addr = config.socket_addr();
111 assert_eq!(addr.port(), 8080);
112 }
113}