Rust 编程小项目:WebServer 03

视频地址

头条地址:https://www.ixigua.com/i680718929763709798...
B站地址:https://www.bilibili.com/video/BV177411m78...

github地址

https://github.com/anonymousGiga/web-serve...

说明

此部分内容接前面内容Rust 编程小项目:WebServer 02

有选择的响应

fn handle_client(stream: TcpStream) { 
    let mut buffer = [0; 512]; 
    stream.read(&mut buffer).unwrap(); 
    let get = b"GET / HTTP/1.1\r\n"; 
    if buffer.starts_with(get) { 
        let contents = fs::read_to_string("main.html").unwrap(); 
        let response = format!("HTTP/1.1 200 OK\r\n\r\n{}", contents); 
        stream.write(response.as_bytes()).unwrap();
        stream.flush().unwrap(); 
    } else { 
        let status_line = "HTTP/1.1 404 NOT FOUND\r\n\r\n"; 
        let contents = fs::read_to_string("404.html").unwrap();
        let response = format!("{}{}", status_line, contents);
        stream.write(response.as_bytes()).unwrap();
        stream.flush().unwrap(); 
    } 
}

对应的404.html

<!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>
本作品采用《CC 协议》,转载必须注明作者和本文链接

令狐一冲

讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!