]> piware.de Git - learn-rust.git/commitdiff
async-http: Initial sync version
authorMartin Pitt <martin@piware.de>
Fri, 16 Sep 2022 06:04:56 +0000 (08:04 +0200)
committerMartin Pitt <martin@piware.de>
Fri, 16 Sep 2022 06:04:56 +0000 (08:04 +0200)
async-http/404.html [new file with mode: 0644]
async-http/Cargo.toml [new file with mode: 0644]
async-http/index.html [new file with mode: 0644]
async-http/src/main.rs [new file with mode: 0644]

diff --git a/async-http/404.html b/async-http/404.html
new file mode 100644 (file)
index 0000000..d59a923
--- /dev/null
@@ -0,0 +1,11 @@
+<!DOCTYPE html>
+<html lang="en">
+  <head>
+    <meta charset="utf-8">
+    <title>Hello!</title>
+  </head>
+  <body>
+    <h1>Oops!</h1>
+    <p>I don't know about this resource.</p>
+  </body>
+</html>
diff --git a/async-http/Cargo.toml b/async-http/Cargo.toml
new file mode 100644 (file)
index 0000000..9c26aaa
--- /dev/null
@@ -0,0 +1,8 @@
+[package]
+name = "async-http"
+version = "0.1.0"
+edition = "2021"
+
+# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
+
+[dependencies]
diff --git a/async-http/index.html b/async-http/index.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/async-http/src/main.rs b/async-http/src/main.rs
new file mode 100644 (file)
index 0000000..09ca609
--- /dev/null
@@ -0,0 +1,39 @@
+use std::fs;
+use std::io::prelude::*;
+use std::net::TcpListener;
+use std::net::TcpStream;
+
+fn main() {
+    // Listen for incoming TCP connections on localhost port 7878
+    let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
+
+    // Block forever, handling each request that arrives at this IP address
+    for stream in listener.incoming() {
+        let stream = stream.unwrap();
+
+        handle_connection(stream);
+    }
+}
+
+fn handle_connection(mut stream: TcpStream) {
+    // Read the first 1024 bytes of data from the stream
+    let mut buffer = [0; 1024];
+    stream.read(&mut buffer).unwrap();
+
+    let get = b"GET / HTTP/1.1\r\n";
+
+    // Respond with greetings or a 404,
+    // depending on the data in the request
+    let (status_line, filename) = if buffer.starts_with(get) {
+        ("HTTP/1.1 200 OK\r\n\r\n", "index.html")
+    } else {
+        ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html")
+    };
+    let contents = fs::read_to_string(filename).unwrap();
+
+    // Write response back to the stream,
+    // and flush the stream to ensure the response is sent back to the client
+    let response = format!("{status_line}{contents}");
+    stream.write_all(response.as_bytes()).unwrap();
+    stream.flush().unwrap();
+}