Skip to content

Commit

Permalink
Updated listings based on listing-20-24
Browse files Browse the repository at this point in the history
Updated `main.rs` in both `listing-20-25` and `no-listing-07-final-code` based on `listing-20-24`
  • Loading branch information
chris-t-jansen committed Apr 3, 2024
1 parent 99ed77b commit a14b540
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 33 deletions.
46 changes: 20 additions & 26 deletions listings/ch20-web-server/listing-20-25/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
use hello::ThreadPool;
use std::fs;
use std::io::prelude::*;
use std::net::TcpListener;
use std::net::TcpStream;
use std::thread;
use std::time::Duration;
use std::{
fs,
io::{prelude::*, BufReader},
net::{TcpListener, TcpStream},
thread,
time::Duration,
};

// ANCHOR: here
fn main() {
Expand All @@ -24,30 +25,23 @@ fn main() {
// ANCHOR_END: here

fn handle_connection(mut stream: TcpStream) {
let mut buffer = [0; 1024];
stream.read(&mut buffer).unwrap();

let get = b"GET / HTTP/1.1\r\n";
let sleep = b"GET /sleep HTTP/1.1\r\n";

let (status_line, filename) = if buffer.starts_with(get) {
("HTTP/1.1 200 OK", "hello.html")
} else if buffer.starts_with(sleep) {
thread::sleep(Duration::from_secs(5));
("HTTP/1.1 200 OK", "hello.html")
} else {
("HTTP/1.1 404 NOT FOUND", "404.html")
let buf_reader = BufReader::new(&mut stream);
let request_line = buf_reader.lines().next().unwrap().unwrap();

let (status_line, filename) = match &request_line[..] {
"GET / HTTP/1.1" => ("HTTP/1.1 200 OK", "hello.html"),
"GET /sleep HTTP/1.1" => {
thread::sleep(Duration::from_secs(5));
("HTTP/1.1 200 OK", "hello.html")
}
_ => ("HTTP/1.1 404 NOT FOUND", "404.html"),
};

let contents = fs::read_to_string(filename).unwrap();
let length = contents.len();

let response = format!(
"{}\r\nContent-Length: {}\r\n\r\n{}",
status_line,
contents.len(),
contents
);
let response =
format!("{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}");

stream.write_all(response.as_bytes()).unwrap();
stream.flush().unwrap();
}
9 changes: 2 additions & 7 deletions listings/ch20-web-server/no-listing-07-final-code/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,8 @@ fn handle_connection(mut stream: TcpStream) {
let contents = fs::read_to_string(filename).unwrap();
let length = contents.len();

let response = format!(
"{}\r\nContent-Length: {}\r\n\r\n{}",
status_line,
length,
contents
);
let response =
format!("{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}");

stream.write_all(response.as_bytes()).unwrap();
stream.flush().unwrap();
}

0 comments on commit a14b540

Please sign in to comment.