Skip to content

Commit

Permalink
Added Content-Length header to Ch 20-01 listings.
Browse files Browse the repository at this point in the history
  • Loading branch information
apogeeoak committed Jan 26, 2021
1 parent e724bd8 commit 395c1b8
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 9 deletions.
9 changes: 7 additions & 2 deletions listings/ch20-web-server/listing-20-07/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,15 @@ fn handle_connection(mut stream: TcpStream) {
// ANCHOR: here
// --snip--
} else {
let status_line = "HTTP/1.1 404 NOT FOUND\r\n\r\n";
let status_line = "HTTP/1.1 404 NOT FOUND";
let contents = fs::read_to_string("404.html").unwrap();

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

stream.write(response.as_bytes()).unwrap();
stream.flush().unwrap();
Expand Down
11 changes: 8 additions & 3 deletions listings/ch20-web-server/listing-20-09/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,14 +27,19 @@ fn handle_connection(mut stream: TcpStream) {

// ANCHOR: here
let (status_line, filename) = if buffer.starts_with(get) {
("HTTP/1.1 200 OK\r\n\r\n", "hello.html")
("HTTP/1.1 200 OK", "hello.html")
} else {
("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html")
("HTTP/1.1 404 NOT FOUND", "404.html")
};

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

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

stream.write(response.as_bytes()).unwrap();
stream.flush().unwrap();
Expand Down
8 changes: 4 additions & 4 deletions src/ch20-01-single-threaded.md
Original file line number Diff line number Diff line change
Expand Up @@ -390,10 +390,10 @@ indicating the response to the end user.
error page if anything other than */* was requested</span>

Here, our response has a status line with status code 404 and the reason
phrase `NOT FOUND`. We’re still not returning headers, and the body of the
response will be the HTML in the file *404.html*. You’ll need to create a
*404.html* file next to *hello.html* for the error page; again feel free to use
any HTML you want or use the example HTML in Listing 20-8.
phrase `NOT FOUND`. The body of the response will be the HTML in the file
*404.html*. You’ll need to create a *404.html* file next to *hello.html* for
the error page; again feel free to use any HTML you want or use the example
HTML in Listing 20-8.

<span class="filename">Filename: 404.html</span>

Expand Down

0 comments on commit 395c1b8

Please sign in to comment.