summaryrefslogtreecommitdiffstats
path: root/src/doc/book/listings/ch20-web-server/listing-20-06
diff options
context:
space:
mode:
Diffstat (limited to 'src/doc/book/listings/ch20-web-server/listing-20-06')
-rw-r--r--src/doc/book/listings/ch20-web-server/listing-20-06/Cargo.lock6
-rw-r--r--src/doc/book/listings/ch20-web-server/listing-20-06/Cargo.toml6
-rw-r--r--src/doc/book/listings/ch20-web-server/listing-20-06/hello.html11
-rw-r--r--src/doc/book/listings/ch20-web-server/listing-20-06/src/main.rs37
4 files changed, 60 insertions, 0 deletions
diff --git a/src/doc/book/listings/ch20-web-server/listing-20-06/Cargo.lock b/src/doc/book/listings/ch20-web-server/listing-20-06/Cargo.lock
new file mode 100644
index 000000000..f2d069f46
--- /dev/null
+++ b/src/doc/book/listings/ch20-web-server/listing-20-06/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-06/Cargo.toml b/src/doc/book/listings/ch20-web-server/listing-20-06/Cargo.toml
new file mode 100644
index 000000000..fe619478a
--- /dev/null
+++ b/src/doc/book/listings/ch20-web-server/listing-20-06/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-06/hello.html b/src/doc/book/listings/ch20-web-server/listing-20-06/hello.html
new file mode 100644
index 000000000..fe442d6b9
--- /dev/null
+++ b/src/doc/book/listings/ch20-web-server/listing-20-06/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-06/src/main.rs b/src/doc/book/listings/ch20-web-server/listing-20-06/src/main.rs
new file mode 100644
index 000000000..5523a42d7
--- /dev/null
+++ b/src/doc/book/listings/ch20-web-server/listing-20-06/src/main.rs
@@ -0,0 +1,37 @@
+use std::{
+ fs,
+ io::{prelude::*, BufReader},
+ net::{TcpListener, TcpStream},
+};
+
+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
+// --snip--
+
+fn handle_connection(mut stream: TcpStream) {
+ let buf_reader = BufReader::new(&mut stream);
+ let request_line = buf_reader.lines().next().unwrap().unwrap();
+
+ if request_line == "GET / HTTP/1.1" {
+ 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();
+ } else {
+ // some other request
+ }
+}
+// ANCHOR_END: here