server_env_config/server.rs
1//! The [`HttpServerConfig`] struct represents configuration for an HTTP server.
2
3use crate::env_parsable;
4
5use anyhow::Result;
6use std::env;
7
8/// Basic configuration for an HTTP server.
9#[derive(Debug, Clone)]
10pub struct HttpServerConfig {
11 /// Host address, may be set by the `HOST` environment variable,
12 /// requests will be limited to the address passed. Setting
13 /// it to "0" means requests can be received from anywhere.
14 pub addr: String,
15 /// Host port, may be set by the `PORT` environment variable
16 pub port: u16,
17 /// API URI (e.g. "/api"), may be set by the `APP_URI` environment variable
18 pub uri: String,
19 /// Final URL parsed: "http://{addr}:{port}/{uri}"
20 pub url: String,
21}
22
23impl HttpServerConfig {
24 /// Initialize the configuration with the env variables `HOST`
25 /// (otherwise default_host) and `PORT` (otherwise use default_port),
26 /// and the env variable `APP_URI` is used to se the `uri`, otherwise
27 /// defaulted to empty string.
28 pub fn init_for(default_host: &str, default_port: u16) -> Result<HttpServerConfig> {
29 let addr = env::var("HOST").unwrap_or(default_host.to_string());
30 let port = env_parsable::<u16>("PORT", default_port)?;
31 let uri = env::var("APP_URI").unwrap_or("".to_string());
32 let url = format!("http://{}{}{}/",
33 if addr == "0" { "localhost" } else { &addr },
34 if port == 80 { "".to_string() } else { format!(":{}", port) },
35 if uri.is_empty() { "".to_string() } else { format!("/{}", uri) });
36 Ok(HttpServerConfig { addr, port, uri, url })
37 }
38}
39
40impl ToString for HttpServerConfig {
41 /// This `to_string()` implementation prints out all the config
42 /// values in `.env` format, using as key the environment variable
43 /// used to set-up the config, even if the configuration was
44 /// set in another way, e.g. using a default value.
45 fn to_string(&self) -> String {
46 format!(
47r#"# APP_URL --> {}
48APP_URI="{}"
49HOST={}
50PORT={}"#,
51 self.url,
52 self.uri,
53 self.addr,
54 self.port,
55 )
56 }
57}