add ServerConfig with env variables
This commit is contained in:
10
src/config.rs
Normal file
10
src/config.rs
Normal file
@@ -0,0 +1,10 @@
|
||||
use bon::Builder;
|
||||
|
||||
#[derive(Debug, Builder)]
|
||||
pub struct ServerConfig {
|
||||
#[builder(default = String::from("0.0.0.0"))]
|
||||
pub host: String,
|
||||
#[builder(default = 6171)]
|
||||
pub port: u16,
|
||||
pub max_connections: Option<usize>,
|
||||
}
|
||||
20
src/main.rs
20
src/main.rs
@@ -1,8 +1,10 @@
|
||||
use config::ServerConfig;
|
||||
use errors::AppError;
|
||||
use server::Server;
|
||||
|
||||
pub mod client;
|
||||
pub mod commands;
|
||||
pub mod config;
|
||||
pub mod connection;
|
||||
pub mod database;
|
||||
pub mod errors;
|
||||
@@ -13,7 +15,23 @@ pub type Result<T> = std::result::Result<T, AppError>;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<()> {
|
||||
let mut server = Server::new("127.0.0.1:6171").await?;
|
||||
let config = ServerConfig::builder()
|
||||
.maybe_host(std::env::var("SERVER_HOST").ok())
|
||||
.maybe_port(
|
||||
std::env::var("SERVER_PORT")
|
||||
.ok()
|
||||
.map(|v| v.parse().ok())
|
||||
.flatten(),
|
||||
)
|
||||
.maybe_max_connections(
|
||||
std::env::var("MAX_CONNECTIONS")
|
||||
.ok()
|
||||
.map(|v| v.parse().ok())
|
||||
.flatten(),
|
||||
)
|
||||
.build();
|
||||
|
||||
let mut server = Server::new(config).await?;
|
||||
|
||||
server.run().await?;
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ use tokio::net::ToSocketAddrs;
|
||||
use tokio::{net::TcpListener, sync::Semaphore};
|
||||
|
||||
use crate::Result;
|
||||
use crate::config::ServerConfig;
|
||||
use crate::connection::Connection;
|
||||
use crate::database::Database;
|
||||
use crate::handler::Handler;
|
||||
@@ -16,14 +17,23 @@ pub struct Server {
|
||||
}
|
||||
|
||||
impl Server {
|
||||
const MAX_CONNECTIONS: usize = 256;
|
||||
pub const MAX_CONNECTIONS: usize = 256;
|
||||
|
||||
pub async fn new<Addr: ToSocketAddrs>(addr: Addr) -> Result<Self> {
|
||||
pub async fn new(config: ServerConfig) -> Result<Self> {
|
||||
let addr = format!("{}:{}", config.host, config.port);
|
||||
Self::_new(
|
||||
addr,
|
||||
config.max_connections.unwrap_or(Self::MAX_CONNECTIONS),
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn _new<Addr: ToSocketAddrs>(addr: Addr, max_connections: usize) -> Result<Self> {
|
||||
let listener = TcpListener::bind(addr).await?;
|
||||
|
||||
Ok(Self {
|
||||
db: Database::new(),
|
||||
connection_limit: Arc::new(Semaphore::const_new(Self::MAX_CONNECTIONS)),
|
||||
connection_limit: Arc::new(Semaphore::const_new(max_connections)),
|
||||
listener,
|
||||
})
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user