mirror of https://github.com/KaiserY/trpl-zh-cn
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
53 lines
1.2 KiB
53 lines
1.2 KiB
// ANCHOR: here
|
|
use std::{
|
|
fs,
|
|
io::{prelude::*, BufReader},
|
|
net::{TcpListener, TcpStream},
|
|
thread,
|
|
time::Duration,
|
|
};
|
|
// --snip--
|
|
// ANCHOR_END: here
|
|
|
|
fn main() {
|
|
let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
|
|
|
|
for stream in listener.incoming() {
|
|
let stream = stream.unwrap();
|
|
|
|
handle_connection(stream);
|
|
}
|
|
}
|
|
// ANCHOR: here
|
|
|
|
fn handle_connection(mut stream: TcpStream) {
|
|
// --snip--
|
|
|
|
// ANCHOR_END: here
|
|
let buf_reader = BufReader::new(&stream);
|
|
let request_line = buf_reader.lines().next().unwrap().unwrap();
|
|
|
|
// ANCHOR: here
|
|
let (status_line, filename) = match &request_line[..] {
|
|
"GET / HTTP/1.1" => ("HTTP/1.1 200 OK", "hello.html"),
|
|
"GET /sleep HTTP/1.1" => {
|
|
thread::sleep(Duration::from_secs(5));
|
|
("HTTP/1.1 200 OK", "hello.html")
|
|
}
|
|
_ => ("HTTP/1.1 404 NOT FOUND", "404.html"),
|
|
};
|
|
|
|
// --snip--
|
|
// ANCHOR_END: here
|
|
|
|
let contents = fs::read_to_string(filename).unwrap();
|
|
let length = contents.len();
|
|
|
|
let response =
|
|
format!("{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}");
|
|
|
|
stream.write_all(response.as_bytes()).unwrap();
|
|
// ANCHOR: here
|
|
}
|
|
// ANCHOR_END: here
|