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.
39 lines
923 B
39 lines
923 B
4 years ago
|
// ANCHOR: here
|
||
3 years ago
|
use std::{
|
||
|
fs,
|
||
|
io::{prelude::*, BufReader},
|
||
|
net::{TcpListener, TcpStream},
|
||
|
};
|
||
4 years ago
|
// --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) {
|
||
9 months ago
|
let buf_reader = BufReader::new(&stream);
|
||
3 years ago
|
let http_request: Vec<_> = buf_reader
|
||
|
.lines()
|
||
|
.map(|result| result.unwrap())
|
||
|
.take_while(|line| !line.is_empty())
|
||
|
.collect();
|
||
|
|
||
|
let status_line = "HTTP/1.1 200 OK";
|
||
4 years ago
|
let contents = fs::read_to_string("hello.html").unwrap();
|
||
3 years ago
|
let length = contents.len();
|
||
4 years ago
|
|
||
3 years ago
|
let response =
|
||
|
format!("{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}");
|
||
4 years ago
|
|
||
3 years ago
|
stream.write_all(response.as_bytes()).unwrap();
|
||
4 years ago
|
}
|
||
|
// ANCHOR_END: here
|