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
72
extern crate ctrlc;

use self::error::Error;
mod error;
pub use self::path::Path;
mod path;

use self::http::{Response};
pub mod http;

//use self::api::{ApiResponse};
mod api;

extern crate tokio;
use tokio::net::{TcpListener, TcpStream};
//use tokio::io::AsyncWriteExt;
//use std::io::prelude::*;

pub struct Server {
    paths: Vec<(String, Path)>
}

impl Server {
    pub fn new() -> Server {
        Server {paths: Vec::new()}
    }

    pub async fn run(&self) -> Result<(), Error> {
        let listener = TcpListener::bind("127.0.0.1:8080").await.unwrap();

        // ctrl + c handler
        ctrlc::set_handler(|| {
            panic!("Panics other thread");
        }).unwrap();

        loop {
            let (socket, _) = listener.accept().await.unwrap();

            tokio::spawn(Server::socket_handler(socket));
        }
    }

    async fn socket_handler(socket: TcpStream) -> Result<(), Error> {
        // We wait for the stream to be writable...
        
        loop {
            // Wait for the socket to be writable
            socket.writable().await.unwrap();
    
            // Try to write data, this may still fail with `WouldBlock`
            // if the readiness event is a false positive.
            match socket.try_write(&Response::new().body(b"<div>Hello!!!</div>").serialize()) {
            //match socket.try_write(b"Hola mundo\n") {
                Ok(_n) => {
                    break;
                }
                Err(ref e) if e.kind() == tokio::io::ErrorKind::WouldBlock => {
                    println!("Writing second");
                    continue;
                }
                Err(e) => panic!("{}", e)
            }
        }
        //socket.shutdown();
        Ok(())
    }

    pub fn path(mut self, path: Path) -> Self {
        self.paths.push((path.get_root(), path));
        self
    }
}