use std::io::{Write, Read, BufReader, BufRead, Result}; use std::net::{TcpListener, TcpStream}; use std::fs; use std::string::{String}; use std::str; fn get_page(request: String) -> String { // To-do: Make this able to load other pages // // The loaded page should be left immutable as it does // not need to be modified by the server. let mut filename = "index.html"; let page = fs::read_to_string(filename); match page { Ok(i) => i.to_string(), Err(e) => "
The resource you are trying to locate cannot be accessed!
".to_string(), } } fn read_stream(mut stream: TcpStream) { // To-do: move streaming reading here return; } fn serve(mut stream: TcpStream) { // To-do: Make a header generator to feed into response. let mut request = Vec::new(); let mut reader = BufReader::new(&mut stream); reader .read_until(b'\n', &mut request) .expect("Failed to read from stream!"); // println!("{}", String::from_utf8_lossy(&request)); let contents = get_page(String::from_utf8_lossy(&request).to_string()); let header = "HTTP/1.1 200 OK\r\n\r\n"; let response = format!("{}{}", header, contents); stream.write(response.as_bytes()).unwrap(); stream.flush().unwrap(); } fn main() -> std::io::Result<()> { let listen = TcpListener::bind("127.0.0.1:8080")?; for stream in listen.incoming() { println!("Serving incoming stream."); serve(stream?); } Ok(()) }