]> piware.de Git - learn-rust.git/blob - simple-http/src/main.rs
simple-http: Check hardcoded root path, add 404 page
[learn-rust.git] / simple-http / src / main.rs
1 use std::io::prelude::*;
2
3 use std::net::TcpListener;
4 use std::net::TcpStream;
5 use std::fs;
6
7 fn handle_connection(mut stream: TcpStream) {
8      let mut buffer = [0; 1024];
9      let get_root = b"GET / HTTP/1.1\r\n";
10
11     stream.read(&mut buffer).unwrap();
12     println!("Request: {}", String::from_utf8_lossy(&buffer[..]));
13
14     let (code, file) = if buffer.starts_with(get_root) {
15         ("200 OK", "hello.html")
16     } else {
17         ("404 NOT FOUND", "404.html")
18     };
19
20     let text = fs::read_to_string(file).unwrap();
21
22     let response = format!(
23         "HTTP/1.1 {}\r\n\
24          Content-Type: text/html\r\n\
25          Content-Length: {}\r\n\r\n{}",
26         code,
27         text.len(),
28         text);
29
30     stream.write(response.as_bytes()).unwrap();
31     stream.flush().unwrap();
32 }
33
34 fn main() {
35     let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
36
37     for stream in listener.incoming() {
38         let stream = stream.unwrap();
39         handle_connection(stream);
40     }
41 }