herb/src/main.rs

58 lines
1.4 KiB
Rust
Raw Normal View History

2021-08-30 17:18:22 +01:00
use std::io::{Write, Read, BufReader, BufRead, Result};
2021-08-29 16:07:05 +01:00
use std::net::{TcpListener, TcpStream};
2021-08-30 16:17:11 +01:00
use std::fs;
use std::string::{String};
2021-08-30 17:18:22 +01:00
use std::str;
2021-08-30 16:17:11 +01:00
fn get_page(request: String) -> String {
2021-08-30 16:17:11 +01:00
// 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";
2021-08-30 16:17:11 +01:00
let page = fs::read_to_string(filename);
match page {
Ok(i) => i.to_string(),
Err(e) => "<!DOCTYPE HTML><html><body><h1>404 Not Found</h1><p>The resource you are trying to locate cannot be accessed!</p></body></html>".to_string(),
}
2021-08-30 16:17:11 +01:00
}
2021-08-29 16:07:05 +01:00
fn read_stream(mut stream: TcpStream) {
// To-do: move streaming reading here
return;
2021-08-30 17:18:22 +01:00
}
2021-08-29 16:07:05 +01:00
fn serve(mut stream: TcpStream) {
2021-08-30 16:17:11 +01:00
// To-do: Make a header generator to feed into response.
2021-08-30 17:18:22 +01:00
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!");
2021-08-30 17:18:22 +01:00
// println!("{}", String::from_utf8_lossy(&request));
2021-08-30 17:18:22 +01:00
let contents = get_page(String::from_utf8_lossy(&request).to_string());
2021-08-30 16:17:11 +01:00
let header = "HTTP/1.1 200 OK\r\n\r\n";
let response = format!("{}{}", header, contents);
2021-08-29 16:07:05 +01:00
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() {
2021-08-30 17:18:22 +01:00
println!("Serving incoming stream.");
2021-08-29 16:07:05 +01:00
serve(stream?);
}
Ok(())
2021-08-29 15:18:20 +01:00
}