From 02ebd7c33029bfbf8112cd8cb2649ca2ef2cd9d2 Mon Sep 17 00:00:00 2001 From: Martin Pitt Date: Mon, 30 Aug 2021 19:39:44 +0200 Subject: [PATCH 1/1] simple-http: Initial skeleton --- simple-http/Cargo.toml | 8 ++++++++ simple-http/hello.html | 11 +++++++++++ simple-http/src/main.rs | 33 +++++++++++++++++++++++++++++++++ 3 files changed, 52 insertions(+) create mode 100644 simple-http/Cargo.toml create mode 100644 simple-http/hello.html create mode 100644 simple-http/src/main.rs diff --git a/simple-http/Cargo.toml b/simple-http/Cargo.toml new file mode 100644 index 0000000..51d0714 --- /dev/null +++ b/simple-http/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "simple-http" +version = "0.1.0" +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/simple-http/hello.html b/simple-http/hello.html new file mode 100644 index 0000000..fe442d6 --- /dev/null +++ b/simple-http/hello.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Hello!

+

Hi from Rust

+ + 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); + } +} -- 2.39.2