2
0
mirror of https://github.com/gnu4cn/rust-lang-zh_CN.git synced 2025-03-21 06:40:29 +08:00
rust-lang-zh_CN/hello/src/main.rs

41 lines
1.0 KiB
Rust
Raw Normal View History

2023-03-27 14:33:48 +08:00
#![allow(warnings)]
use std::{
fs,
io::{prelude::*, BufReader},
net::{TcpListener, TcpStream},
2023-03-30 13:56:25 +08:00
thred,
time::Duration,
2023-03-27 14:33:48 +08:00
};
fn main() {
let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
for stream in listener.incoming() {
let stream = stream.unwrap();
handle_conn(stream);
}
}
fn handle_conn(mut stream: TcpStream) {
let buf_reader = BufReader::new(&mut stream);
let req_line = buf_reader.lines().next().unwrap().unwrap();
2023-03-30 13:56:25 +08:00
let (status_line, filename) = match &req_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 0K", "hello.html")
}
_ => ("HTTP/1.1 404 NOT FOUND", "404.html"),
2023-03-27 14:33:48 +08:00
};
let contents = fs::read_to_string(filename).unwrap();
let length = contents.len();
let resp =
format! ("{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}");
stream.write_all(resp.as_bytes()).unwrap();
}