1use std::sync::Arc;
2use tokio::io::AsyncWriteExt;
3use crate::utils::{request::parse_request_data, response::handle_response, router::Router};
4
5pub struct App {
6 endpoints: Option<Arc<dyn Fn(&mut Router) + Send + Sync>>,
7}
8
9impl App {
10 pub fn new() -> Self {
11 Self {
12 endpoints: None,
13 }
14 }
15
16 pub fn endpoints<F>(&mut self, endpoints: F)
17 where
18 F: Fn(&mut Router) + Send + Sync + 'static,
19 {
20 self.endpoints = Some(Arc::new(endpoints));
21 }
22
23 pub async fn run(self, port: i128) {
24 let listener = tokio::net::TcpListener::bind(&format!("0.0.0.0:{port}"))
25 .await
26 .expect("Error while binding connection to public address");
27 println!("Server is running at: http://localhost:{}", port);
28
29 let app_ref = Arc::new(self);
30 loop {
31 let (mut stream, _) = listener
32 .accept()
33 .await
34 .expect("Failed to accept the client's established connection");
35 let app = Arc::clone(&app_ref);
36 tokio::spawn(async move {
37 app.handle_stream(&mut stream).await;
38 });
39 }
40 }
41
42 async fn handle_stream(&self, stream: &mut tokio::net::TcpStream) {
43 let request = parse_request_data(stream).await;
44 let mut router = Router::new();
45
46 if let Some(ref endpoints) = self.endpoints {
48 endpoints(&mut router);
49 }
50
51 handle_response(stream, &request, &router).await;
52 stream.flush().await.expect("Failed to flush stream");
53 }
54}