summaryrefslogtreecommitdiffstats
path: root/src/doc/book/listings/ch20-web-server/listing-20-05
diff options
context:
space:
mode:
Diffstat (limited to 'src/doc/book/listings/ch20-web-server/listing-20-05')
-rw-r--r--src/doc/book/listings/ch20-web-server/listing-20-05/Cargo.lock6
-rw-r--r--src/doc/book/listings/ch20-web-server/listing-20-05/Cargo.toml6
-rw-r--r--src/doc/book/listings/ch20-web-server/listing-20-05/hello.html11
-rw-r--r--src/doc/book/listings/ch20-web-server/listing-20-05/src/main.rs38
4 files changed, 61 insertions, 0 deletions
diff --git a/src/doc/book/listings/ch20-web-server/listing-20-05/Cargo.lock b/src/doc/book/listings/ch20-web-server/listing-20-05/Cargo.lock
new file mode 100644
index 000000000..f2d069f46
--- /dev/null
+++ b/src/doc/book/listings/ch20-web-server/listing-20-05/Cargo.lock
@@ -0,0 +1,6 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+[[package]]
+name = "hello"
+version = "0.1.0"
+
diff --git a/src/doc/book/listings/ch20-web-server/listing-20-05/Cargo.toml b/src/doc/book/listings/ch20-web-server/listing-20-05/Cargo.toml
new file mode 100644
index 000000000..fe619478a
--- /dev/null
+++ b/src/doc/book/listings/ch20-web-server/listing-20-05/Cargo.toml
@@ -0,0 +1,6 @@
+[package]
+name = "hello"
+version = "0.1.0"
+edition = "2021"
+
+[dependencies]
diff --git a/src/doc/book/listings/ch20-web-server/listing-20-05/hello.html b/src/doc/book/listings/ch20-web-server/listing-20-05/hello.html
new file mode 100644
index 000000000..fe442d6b9
--- /dev/null
+++ b/src/doc/book/listings/ch20-web-server/listing-20-05/hello.html
@@ -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/src/doc/book/listings/ch20-web-server/listing-20-05/src/main.rs b/src/doc/book/listings/ch20-web-server/listing-20-05/src/main.rs
new file mode 100644
index 000000000..d4b78b640
--- /dev/null
+++ b/src/doc/book/listings/ch20-web-server/listing-20-05/src/main.rs
@@ -0,0 +1,38 @@
+// ANCHOR: here
+use std::{
+ fs,
+ io::{prelude::*, BufReader},
+ net::{TcpListener, TcpStream},
+};
+// --snip--
+
+// ANCHOR_END: here
+fn main() {
+ let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
+
+ for stream in listener.incoming() {
+ let stream = stream.unwrap();
+
+ handle_connection(stream);
+ }
+}
+
+// ANCHOR: here
+fn handle_connection(mut stream: TcpStream) {
+ let buf_reader = BufReader::new(&mut stream);
+ let http_request: Vec<_> = buf_reader
+ .lines()
+ .map(|result| result.unwrap())
+ .take_while(|line| !line.is_empty())
+ .collect();
+
+ let status_line = "HTTP/1.1 200 OK";
+ let contents = fs::read_to_string("hello.html").unwrap();
+ let length = contents.len();
+
+ let response =
+ format!("{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}");
+
+ stream.write_all(response.as_bytes()).unwrap();
+}
+// ANCHOR_END: here