Skip to content

Commit 7ca16a2

Browse files
committed
c20: single-thread web server
1 parent 1d80f8d commit 7ca16a2

File tree

4 files changed

+64
-0
lines changed

4 files changed

+64
-0
lines changed

c20_web_server/404.html

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
<head>
4+
<meta charset="utf-8">
5+
<title>Hello!</title>
6+
</head>
7+
<body>
8+
<h1>Oops!</h1>
9+
<p>Not available.</p>
10+
</body>
11+
</html>

c20_web_server/Cargo.toml

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
[package]
2+
name = "c20_web_server"
3+
version = "0.1.0"
4+
edition = "2021"
5+
6+
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
7+
8+
[dependencies]

c20_web_server/hello.html

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
<!DOCTYPE html>
2+
<html lang="en">
3+
<head>
4+
<meta charset="utf-8">
5+
<title>Hello!</title>
6+
</head>
7+
<body>
8+
<h1>Hello!</h1>
9+
<p>Hi from Rust</p>
10+
</body>
11+
</html>

c20_web_server/src/main.rs

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
use std::{fs, io::{BufRead, BufReader, Write}, net::{TcpListener, TcpStream}};
2+
3+
4+
fn handle_connection(mut stream: TcpStream) {
5+
let buf_reader = BufReader::new(&mut stream);
6+
let request_line = buf_reader.lines().next().unwrap().unwrap();
7+
8+
// let http_request: Vec<_> = buf_reader
9+
// .lines()
10+
// .map(|result| result.unwrap())
11+
// .take_while(|line| !line.is_empty())
12+
// .collect();
13+
// println!("Request: {:#?}", http_request);
14+
15+
16+
let (status_line, filename) = if request_line == "GET / HTTP/1.1" {
17+
("HTTP/1.1 200 OK", "hello.html")
18+
} else {
19+
("HTTP/1.1 404 NOT FOUND", "404.html")
20+
};
21+
let contents = fs::read_to_string(filename).unwrap();
22+
let length = contents.len();
23+
let response = format!("{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}");
24+
25+
stream.write_all(response.as_bytes()).unwrap();
26+
}
27+
fn main() {
28+
let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
29+
for stream in listener.incoming() {
30+
let stream = stream.unwrap();
31+
32+
handle_connection(stream);
33+
}
34+
}

0 commit comments

Comments
 (0)