server.rs 46 lignes · 1301 octets
use std::env;

/// Server configuration
///
/// Contains configuration for the Axum server including host and port.
/// Configuration is loaded from environment variables with sensible defaults.
#[derive(Debug, Clone)]
pub struct ServerConfig {
    /// Server host address (default: "0.0.0.0")
    pub host: String,
    /// Server port (default: 3000)
    pub port: u16,
}

impl ServerConfig {
    /// Create a new ServerConfig from environment variables
    ///
    /// # Returns
    ///
    /// A `ServerConfig` instance with values from environment variables
    /// or defaults if not set.
    ///
    /// # Environment Variables
    ///
    /// - `SERVER_HOST`: Server host address (default: "0.0.0.0")
    /// - `SERVER_PORT`: Server port number (default: 3000)
    pub fn from_env() -> Self {
        let host = env::var("SERVER_HOST").unwrap_or_else(|_| "0.0.0.0".to_string());

        let port = env::var("SERVER_PORT")
            .unwrap_or_else(|_| "3000".to_string())
            .parse::<u16>()
            .unwrap_or(3000);

        Self { host, port }
    }

    /// Get the server address as a string (host:port)
    ///
    /// # Returns
    ///
    /// A string in the format "host:port"
    pub fn address(&self) -> String {
        format!("{}:{}", self.host, self.port)
    }
}