blob: ee71aacf6f69bbd8739e2738f89a86fc1a156213 (
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
|
use std::fs;
use std::io::BufReader;
use std::io::prelude::*;
use std::net::TcpListener;
use std::net::TcpStream;
fn main() {
start_server("127.0.0.1:7878".to_string())
}
pub fn start_server(bind: String) {
let listener = TcpListener::bind(bind).unwrap();
for next_stream in listener.incoming() {
handle(next_stream.unwrap());
}
}
fn handle(mut stream: TcpStream) {
let io = BufReader::new(&stream);
let request_line = io.lines().next().unwrap().unwrap();
let (status_line, filename) = match &request_line[..] {
"GET / HTTP/1.1" => ("HTTP/1.1 200 OK", "./public/index.html"),
_ => ("HTTP/1.1 404 NOT FOUND", "./public/404.html"),
};
let contents = fs::read_to_string(filename).unwrap();
let length = contents.len();
let response = format!("{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}");
stream.write_all(response.as_bytes()).unwrap();
}
#[cfg(test)]
mod tests {
use crate::start_server;
use std::thread;
#[test]
fn it_starts_a_server() {
// TODO:: figure out how to spawn a server in a background thread
// let server = thread::spawn(|| start_server("127.0.0.1:7878".to_string()));
assert!(true);
// server.join().unwrap();
}
}
|