diff --git a/h8r/TODO.md b/h8r/TODO.md index 552ab52..649e2e2 100644 --- a/h8r/TODO.md +++ b/h8r/TODO.md @@ -1,13 +1,13 @@ - [x] server on fixed port responding "oh no" - [x] configurable addr -- [ ] string responses -- [ ] error page paths -- [ ] serve "index.txt" file if exists, else 404 +- [x] serve "index.txt" file if exists, else 404 - [ ] serve relative paths with mime type text/plain - [ ] guess mime type - [ ] configurable working directory +- [ ] string responses - [ ] automatic directory index - [ ] content ranges +- [ ] error page paths - [ ] liquid template rendering - [ ] upstream proxy via prefix - [ ] upstream proxy path match diff --git a/h8r/src/main.rs b/h8r/src/main.rs index 2a206c9..9c60f83 100644 --- a/h8r/src/main.rs +++ b/h8r/src/main.rs @@ -1,8 +1,10 @@ -use std::io::Write; +use std::env; +use std::fs; +use std::io::{self, Write}; use std::net::{Shutdown, TcpListener}; -fn main() -> std::io::Result<()> { - let addr = std::env::var("H8R_ADDR").unwrap_or("127.0.0.1:17321".to_string()); +fn main() -> io::Result<()> { + let addr = env::var("H8R_ADDR").unwrap_or("127.0.0.1:17321".to_string()); let listener = TcpListener::bind(&addr).unwrap(); eprintln!("h8r: listening at {}", addr); @@ -16,19 +18,32 @@ fn main() -> std::io::Result<()> { Ok(()) } -fn handle_conn(stream: &mut impl Write) -> std::io::Result<()> { - eprintln!("attempting to respond"); +fn handle_conn(stream: &mut impl Write) -> io::Result<()> { + eprintln!("h8r: attempting to respond"); - let response = concat![ - "HTTP/1.1 200 OK\r\n", - "content-type: text/plain\r\n", - "\r\n", - "oh no\n", - ]; + let index_res = fs::read_to_string("index.txt"); + if index_res.is_ok() { + let head = concat!["HTTP/1.1 200 OK\r\n", "content-type: text/plain\r\n"]; + let index = index_res.unwrap(); + let index_len = index.len(); + stream.write_all(head.as_bytes()).unwrap(); + stream + .write_all(format!("content-length: {}\r\n", index_len).as_bytes()) + .unwrap(); + stream.write_all("\r\n".as_bytes()).unwrap(); + stream.write_all(index.as_bytes()).unwrap(); + } else { + let response = concat![ + "HTTP/1.1 404 Not Found\r\n", + "content-type: text/plain\r\n", + "\r\n", + "oh no\n", + ]; + + stream.write_all(response.as_bytes()).unwrap(); + } - stream.write_all(response.as_bytes()).unwrap(); stream.flush()?; - Ok(()) } @@ -38,7 +53,7 @@ mod tests { #[test] fn handle_conn_writes_response() { - let mut stream = [100u8].repeat(64_000); + let mut stream = [100u8].repeat(1_000); let _ = handle_conn(&mut stream); assert!(str::from_utf8(&stream).unwrap().contains("oh no")); }