livid_server/
server.rs

1use ascii::AsciiString;
2use std::collections::HashMap;
3use std::fs;
4use std::io::Write;
5use std::path::{Path, PathBuf};
6use tiny_http::{Header, Method, Request, Response, ResponseBox, Server as ThServer, StatusCode};
7
8fn get_content_type(path: &Path) -> &'static str {
9    let extension = match path.extension() {
10        None => return "text/plain",
11        Some(e) => e,
12    };
13
14    match extension.to_str().unwrap() {
15        "gif" => "image/gif",
16        "jpg" => "image/jpeg",
17        "jpeg" => "image/jpeg",
18        "png" => "image/png",
19        "pdf" => "application/pdf",
20        "htm" => "text/html; charset=utf8",
21        "html" => "text/html; charset=utf8",
22        "txt" => "text/plain; charset=utf8",
23        "js" => "application/javascript",
24        "css" => "text/css",
25        "wasm" => "application/wasm",
26        _ => "text/plain; charset=utf8",
27    }
28}
29
30type Routes = HashMap<(Method, String), fn(rq: &mut Request) -> ResponseBox>;
31
32pub struct Server {
33    port: u16,
34    root: Option<PathBuf>,
35    output: Option<Box<dyn Write>>,
36    routes: Routes,
37}
38
39impl Server {
40    pub fn new(port: u16) -> Self {
41        Self {
42            port,
43            root: None,
44            output: None,
45            routes: HashMap::new(),
46        }
47    }
48    pub fn serve_dir<P: AsRef<Path>>(&mut self, dir: &P) {
49        self.root = Some(PathBuf::from(dir.as_ref()));
50    }
51    pub fn log_output(&mut self, o: Box<dyn std::io::Write>) {
52        self.output = Some(o);
53    }
54    pub fn route(&mut self, verb: Method, url: &str, f: fn(rq: &mut Request) -> ResponseBox) {
55        self.routes.insert((verb, url.to_string()), f);
56    }
57    pub fn serve(&mut self) {
58        let server = ThServer::http(&format!("0.0.0.0:{}", self.port)).unwrap();
59        while let Ok(mut rq) = server.recv() {
60            if let Some(output) = self.output.as_mut() {
61                let v = rq.http_version();
62                let ra = rq.remote_addr().unwrap();
63                output.write_all(format!("{:?} - [{}] - \"{} {} HTTP/{}.{}\"", ra.ip(), httpdate::HttpDate::from(std::time::SystemTime::now()), rq.method(), rq.url(), v.0, v.1).as_bytes()).unwrap();
64            }
65            let method = rq.method().clone();
66            let url = rq.url().to_string();
67            if let Some(f) = self.routes.get(&(method.clone(), url)) {
68                let resp = f(&mut rq);
69                let _ = rq.respond(resp);
70            } else if self.root.is_some() && method == Method::Get {
71                let mut url = rq.url().to_string().strip_prefix('/').unwrap().to_string();
72                if url.is_empty() {
73                    url = "index.html".to_string();
74                }
75                let path = Path::new(&url);
76                let npath = self.root.as_ref().unwrap().join(path);
77                let file = fs::File::open(&npath);
78                let code = if let Ok(file) = file {
79                    let response = Response::from_file(file);
80                    let response = response.with_header(Header {
81                        field: "Content-Type".parse().unwrap(),
82                        value: AsciiString::from_ascii(get_content_type(path)).unwrap(),
83                    });
84                    let code = response.status_code();
85                    let _ = rq.respond(response);
86                    code
87                } else {
88                    let response = Response::new_empty(StatusCode(404));
89                    let code = response.status_code();
90                    let _ = rq.respond(response);
91                    code
92                };
93                if let Some(output) = self.output.as_mut() {
94                    output.write_all(&format!(" - {}\n", code.0).as_bytes()).unwrap();
95                    output.flush().unwrap();
96                }
97            }
98        }
99    }
100}