]> piware.de Git - learn-rust.git/blob - simple-http/src/main.rs
simple-http: Initial skeleton
[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
10     stream.read(&mut buffer).unwrap();
11     println!("Request: {}", String::from_utf8_lossy(&buffer[..]));
12
13     let hello_contents = fs::read_to_string("hello.html").unwrap();
14
15     let response = format!(
16         "HTTP/1.1 200 OK\r\n\
17          Content-Type: text/html\r\n\
18          Content-Length: {}\r\n\r\n{}",
19         hello_contents.len(),
20         hello_contents);
21
22     stream.write(response.as_bytes()).unwrap();
23     stream.flush().unwrap();
24 }
25
26 fn main() {
27     let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
28
29     for stream in listener.incoming() {
30         let stream = stream.unwrap();
31         handle_connection(stream);
32     }
33 }