first commit, small server servme

This commit is contained in:
2025-01-16 18:24:43 +01:00
commit 79db275dc9
8 changed files with 570 additions and 0 deletions

50
src/server.rs Normal file
View File

@@ -0,0 +1,50 @@
use crate::{builder::ServerBuilder, config::ServerConfig};
use http_body_util::Full;
use hyper::{body::Incoming, server::conn::http1, service::service_fn, Request, Response};
use hyper_util::rt::{TokioIo, TokioTimer};
use log::error;
use std::{convert::Infallible, future::Future, net::SocketAddr, sync::Arc};
use tokio::{net::TcpListener, spawn};
use tokio_util::bytes::Bytes;
pub struct Server {
pub config: ServerConfig,
}
impl Server {
pub fn builder() -> ServerBuilder {
ServerBuilder {
config: ServerConfig::default(),
}
}
pub async fn run<F, Fut>(self, handler: F)
where
F: Fn(Request<Incoming>) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<Response<Full<Bytes>>, Infallible>> + Send,
{
let addr: SocketAddr = format!("{}:{}", self.config.ip, self.config.port)
.parse()
.expect("Invalid IP or port");
let listener = TcpListener::bind(addr).await.unwrap();
let handler = Arc::new(handler);
loop {
let (tcp, _) = listener.accept().await.unwrap();
let io = TokioIo::new(tcp);
let handler = Arc::clone(&handler);
spawn(async move {
if let Err(error) = http1::Builder::new()
.timer(TokioTimer::new())
.serve_connection(io, service_fn(move |req| handler(req)))
.await
{
error!(error = error.to_string().as_str();
"Serving connection"
);
}
});
}
}
}