Rust 程式設計小專案:WebServer 03

linghuyichong發表於2020-03-23

頭條地址:https://www.ixigua.com/i680718929763709798...
B站地址:https://www.bilibili.com/video/BV177411m78...

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 協議》,轉載必須註明作者和本文連結
令狐一衝

相關文章