X-Git-Url: https://piware.de/gitweb/?p=learn-rust.git;a=blobdiff_plain;f=simple-http%2Fsrc%2Fmain.rs;fp=simple-http%2Fsrc%2Fmain.rs;h=ca624762c2a1005335669710e0ceb54d254d2e3d;hp=0000000000000000000000000000000000000000;hb=02ebd7c33029bfbf8112cd8cb2649ca2ef2cd9d2;hpb=d6fbfabfaf434ae365854f0587547cff3ca78dae diff --git a/simple-http/src/main.rs b/simple-http/src/main.rs new file mode 100644 index 0000000..ca62476 --- /dev/null +++ b/simple-http/src/main.rs @@ -0,0 +1,33 @@ +use std::io::prelude::*; + +use std::net::TcpListener; +use std::net::TcpStream; +use std::fs; + +fn handle_connection(mut stream: TcpStream) { + let mut buffer = [0; 1024]; + + stream.read(&mut buffer).unwrap(); + println!("Request: {}", String::from_utf8_lossy(&buffer[..])); + + let hello_contents = fs::read_to_string("hello.html").unwrap(); + + let response = format!( + "HTTP/1.1 200 OK\r\n\ + Content-Type: text/html\r\n\ + Content-Length: {}\r\n\r\n{}", + hello_contents.len(), + hello_contents); + + stream.write(response.as_bytes()).unwrap(); + stream.flush().unwrap(); +} + +fn main() { + let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); + + for stream in listener.incoming() { + let stream = stream.unwrap(); + handle_connection(stream); + } +}