60 lines
1.7 KiB
Rust
Raw Normal View History

2026-01-24 22:59:20 +00:00
use crate::api::ApiHandler;
use crate::config::Config;
use anyhow::Result;
use hyper::server::conn::Http;
use hyper::service::service_fn;
2026-01-24 22:59:20 +00:00
use std::net::SocketAddr;
use std::sync::Arc;
use tokio::net::TcpListener;
use tracing::error;
2026-01-24 22:59:20 +00:00
pub struct Server {
_config: Config,
2026-01-24 22:59:20 +00:00
api_handler: Arc<ApiHandler>,
}
impl Server {
pub async fn new(config: Config) -> Result<Self> {
let api_handler = Arc::new(ApiHandler::new(config.clone()).await?);
Ok(Self {
_config: config,
2026-01-24 22:59:20 +00:00
api_handler,
})
}
pub async fn serve(&self, addr: SocketAddr) -> Result<()> {
let listener = TcpListener::bind(addr).await?;
loop {
let (stream, peer_addr) = match listener.accept().await {
Ok(conn) => conn,
Err(e) => {
error!("Failed to accept connection: {}", e);
continue;
}
};
let handler = self.api_handler.clone();
tokio::spawn(async move {
let service = service_fn(move |req| {
let handler = handler.clone();
async move {
handler.handle_request(req).await
.map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, format!("{}", e)))
2026-01-24 22:59:20 +00:00
}
});
if let Err(e) = Http::new()
.serve_connection(stream, service)
.with_upgrades()
2026-01-24 22:59:20 +00:00
.await
{
error!("Error serving connection from {}: {}", peer_addr, e);
}
});
}
}
}