Skip to content

Commit 54318d3

Browse files
committed
7th stage: handle not-found
1 parent 056505a commit 54318d3

File tree

1 file changed

+8
-5
lines changed

1 file changed

+8
-5
lines changed

src/main.rs

+8-5
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
use std::io::{Read, Write};
22
use std::net::{TcpListener, TcpStream};
3-
use std::path::{Path, PathBuf};
3+
use std::path::PathBuf;
44
use std::thread;
55

66
use itertools::Itertools;
@@ -88,13 +88,15 @@ fn handle_connection(mut stream: TcpStream, path: Option<PathBuf>) -> Result<(),
8888
stream.write("HTTP/1.1 200 OK\r\n\r\n".as_bytes()).unwrap();
8989
} else if req.path.starts_with("/echo/") {
9090
let txt = &req.path[6..];
91-
send_text_content(&mut stream, txt).unwrap();
91+
send_text_content(&mut stream, txt)?;
9292
} else if req.path.starts_with("/files/") {
9393
let path = path.unwrap_or_else(|| PathBuf::from("."));
9494
let file_path = path.join(&req.path[7..]);
9595

96-
let file = std::fs::read_to_string(file_path)?;
97-
send_content(&mut stream, "application/octet-stream", file);
96+
match std::fs::read_to_string(file_path) {
97+
Ok(file) => send_text_content(&mut stream, &file)?,
98+
Err(_) => not_found(&mut stream)?,
99+
}
98100
} else if req.path == "/user-agent" {
99101
let ua = req
100102
.headers
@@ -103,7 +105,7 @@ fn handle_connection(mut stream: TcpStream, path: Option<PathBuf>) -> Result<(),
103105
.map(|(_, v)| v)
104106
.unwrap_or(&"Unknown");
105107

106-
send_text_content(&mut stream, ua).unwrap();
108+
send_text_content(&mut stream, ua)?;
107109
} else {
108110
not_found(&mut stream)?;
109111
}
@@ -116,6 +118,7 @@ fn handle_connection(mut stream: TcpStream, path: Option<PathBuf>) -> Result<(),
116118
}
117119

118120
#[derive(Debug)]
121+
#[allow(dead_code)]
119122
pub struct Request<'a> {
120123
method: &'a str,
121124
path: &'a str,

0 commit comments

Comments
 (0)