]> piware.de Git - learn-rust.git/blob - async-http/src/main.rs
async-http: Initial sync version
[learn-rust.git] / async-http / src / main.rs
1 use std::fs;
2 use std::io::prelude::*;
3 use std::net::TcpListener;
4 use std::net::TcpStream;
5
6 fn main() {
7     // Listen for incoming TCP connections on localhost port 7878
8     let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
9
10     // Block forever, handling each request that arrives at this IP address
11     for stream in listener.incoming() {
12         let stream = stream.unwrap();
13
14         handle_connection(stream);
15     }
16 }
17
18 fn handle_connection(mut stream: TcpStream) {
19     // Read the first 1024 bytes of data from the stream
20     let mut buffer = [0; 1024];
21     stream.read(&mut buffer).unwrap();
22
23     let get = b"GET / HTTP/1.1\r\n";
24
25     // Respond with greetings or a 404,
26     // depending on the data in the request
27     let (status_line, filename) = if buffer.starts_with(get) {
28         ("HTTP/1.1 200 OK\r\n\r\n", "index.html")
29     } else {
30         ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html")
31     };
32     let contents = fs::read_to_string(filename).unwrap();
33
34     // Write response back to the stream,
35     // and flush the stream to ensure the response is sent back to the client
36     let response = format!("{status_line}{contents}");
37     stream.write_all(response.as_bytes()).unwrap();
38     stream.flush().unwrap();
39 }