added simple single threaded web server.
This commit is contained in:
parent
aec66ef7c8
commit
20406b1d58
11
the_book/http_server/404.html
Normal file
11
the_book/http_server/404.html
Normal file
|
@ -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>
|
8
the_book/http_server/Cargo.toml
Normal file
8
the_book/http_server/Cargo.toml
Normal file
|
@ -0,0 +1,8 @@
|
|||
[package]
|
||||
name = "http_server"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
11
the_book/http_server/hello.html
Normal file
11
the_book/http_server/hello.html
Normal file
|
@ -0,0 +1,11 @@
|
|||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<title>Hello!</title>
|
||||
</head>
|
||||
<body>
|
||||
<h1>Hello!</h1>
|
||||
<p>Hi from Rust</p>
|
||||
</body>
|
||||
</html>
|
46
the_book/http_server/src/main.rs
Normal file
46
the_book/http_server/src/main.rs
Normal file
|
@ -0,0 +1,46 @@
|
|||
use std::fs;
|
||||
use std::time::Duration;
|
||||
use std::thread;
|
||||
use std::io::prelude::*;
|
||||
use std::net::TcpListener;
|
||||
use std::net::TcpStream;
|
||||
|
||||
fn main() {
|
||||
let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
|
||||
|
||||
for stream in listener.incoming() {
|
||||
let stream = stream.unwrap();
|
||||
println!("Connection Established!");
|
||||
handle_connection(stream);
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_connection(mut stream: TcpStream) {
|
||||
let mut buffer = [0; 1024];
|
||||
|
||||
stream.read(&mut buffer).unwrap();
|
||||
println!("Request: {}", String::from_utf8_lossy(&buffer[..]));
|
||||
|
||||
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 contents = fs::read_to_string(filename).unwrap();
|
||||
let response = format!(
|
||||
"{}\r\nContent-Length: {}\r\n\r\n{}",
|
||||
status_line,
|
||||
contents.len(),
|
||||
contents,
|
||||
);
|
||||
|
||||
stream.write_all(response.as_bytes()).unwrap();
|
||||
stream.flush().unwrap();
|
||||
}
|
Loading…
Reference in a new issue