simple-http: Initial skeleton
authorMartin Pitt <martin@piware.de>
Mon, 30 Aug 2021 17:39:44 +0000 (19:39 +0200)
committerMartin Pitt <martin@piware.de>
Mon, 30 Aug 2021 17:39:44 +0000 (19:39 +0200)
simple-http/Cargo.toml [new file with mode: 0644]
simple-http/hello.html [new file with mode: 0644]
simple-http/src/main.rs [new file with mode: 0644]

diff --git a/simple-http/Cargo.toml b/simple-http/Cargo.toml
new file mode 100644 (file)
index 0000000..51d0714
--- /dev/null
@@ -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 (file)
index 0000000..fe442d6
--- /dev/null
@@ -0,0 +1,11 @@
+<!DOCTYPE html>
+<html lang="en">
+  <head>
+    <meta charset="utf-8">
+    <title>Hello!</title>
+  </head>
+  <body>
+    <h1>Hello!</h1>
+    <p>Hi from Rust</p>
+  </body>
+</html>
diff --git a/simple-http/src/main.rs b/simple-http/src/main.rs
new file mode 100644 (file)
index 0000000..ca62476
--- /dev/null
@@ -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);
+    }
+}