Skip to content

Commit

Permalink
Validating the Request and Selectively Responding
Browse files Browse the repository at this point in the history
  • Loading branch information
dhanushrajgp committed Jul 12, 2024
1 parent 3c9756c commit 6b1d936
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 11 deletions.
11 changes: 11 additions & 0 deletions 404.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Hello!</title>
</head>
<body>
<h1>Oops!</h1>
<p>Sorry, I don't know what you're asking for.</p>
</body>
</html>
29 changes: 18 additions & 11 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,17 +15,24 @@ fn main() {

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 request_line = buf_reader.lines().next().unwrap().unwrap();

let status_line = "HTTP/1.1 200 OK";
let contents = fs::read_to_string("hello.html").unwrap();
let length = contents.len();
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\n Content length: {length} \r\n\r\n {contents}");

stream.write_all(response.as_bytes()).unwrap();
let response = format!("{status_line}\r\n Content length: {length} \r\n\r\n {contents}");
stream.write_all(response.as_bytes()).unwrap();
} else {
let status_line = "HTTP/1.1 404 NOT FOUND";
let contents = fs::read_to_string("404.html").unwrap();
let length = contents.len();
let response = format!(
"{status_line}\r\n\
Content-Length: {length}\r\n\r\n
{contents}"
);
stream.write_all(response.as_bytes()).unwrap();
}
}

0 comments on commit 6b1d936

Please sign in to comment.