aboutsummaryrefslogtreecommitdiff
path: root/src/server.rs
blob: 9c60d332a5980bb2b2e4f57cee769971795c8fcb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
use std::io::{self, Read, Write};
use std::net::TcpStream;
use std::str;
use std::{
    collections::HashMap,
    net::{SocketAddr, TcpListener},
};

use nom::AsBytes;

use crate::request::Request;
use crate::router::Router;

pub struct Server {
    address: SocketAddr,
}

impl Server {
    pub fn new(address: SocketAddr) -> Self {
        Self { address }
    }

    pub fn handle_client(
        mut stream: TcpStream,
        router: &Router,
        ctx: Option<&HashMap<String, String>>,
    ) -> io::Result<usize> {
        // Buffer to store the data received from the client
        let mut buffer = [0; 512];

        // Read data from the stream
        match stream.read(&mut buffer) {
            Ok(_) => {
                // Convert buffer to a string and print the received data
                match str::from_utf8(&buffer) {
                    Ok(request) => {
                        println!("Received request:\n{}", request);
                        let request_lines: Vec<&str> = request.split("\r\n").collect();
                        let request = Request::from(request_lines);
                        let request_string: String = (&request).into();

                        println!("Request after parsing:\n{}", request_string);
                        dbg!(&request.method);

                        let response: Vec<u8> = router.handle(&request, ctx).into();
                        stream.write(response.as_bytes())
                    }
                    Err(_) => todo!(),
                }
            }
            Err(_) => todo!(),
        }
    }

    pub fn serve(&self, router: &Router, ctx: Option<&HashMap<String, String>>) -> io::Result<()> {
        let listener = TcpListener::bind(self.address).unwrap();
        for stream in listener.incoming() {
            match stream {
                Ok(stream) => {
                    // thread::spawn(|| {
                    let _ = Server::handle_client(stream, router, ctx);
                    // });
                }
                Err(e) => {
                    eprintln!("error: {}", e);
                }
            }
        }
        Ok(())
    }
}