From 5df6b9e233ed6115269aed08fb27cb9d1cc61e6b Mon Sep 17 00:00:00 2001 From: Dan Buch Date: Sun, 12 Apr 2026 21:58:55 -0400 Subject: [PATCH] Server responds "oh no" --- h8r/TODO.md | 3 +-- h8r/src/main.rs | 43 +++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 42 insertions(+), 4 deletions(-) diff --git a/h8r/TODO.md b/h8r/TODO.md index 53153c8..e232842 100644 --- a/h8r/TODO.md +++ b/h8r/TODO.md @@ -1,5 +1,4 @@ -- [ ] single-request server on fixed port responding "oh no" -- [ ] multi-request server on fixed port responding "oh no" +- [x] server on fixed port responding "oh no" - [ ] configurable port and working directory - [ ] string responses - [ ] error page paths diff --git a/h8r/src/main.rs b/h8r/src/main.rs index e7a11a9..47ee049 100644 --- a/h8r/src/main.rs +++ b/h8r/src/main.rs @@ -1,3 +1,42 @@ -fn main() { - println!("Hello, world!"); +use std::io::Write; +use std::net::{Shutdown, TcpListener}; + +fn handle_conn(stream: &mut impl Write) -> std::io::Result<()> { + eprintln!("attempting to respond"); + + let response = concat![ + "HTTP/1.1 200 OK\r\n", + "content-type: text/plain\r\n", + "\r\n", + "oh no\n", + ]; + + stream.write_all(response.as_bytes()).unwrap(); + stream.flush()?; + + Ok(()) +} + +fn main() -> std::io::Result<()> { + let listener = TcpListener::bind("127.0.0.1:17321").unwrap(); + + for stream in listener.incoming() { + let mut stream = stream.unwrap(); + handle_conn(&mut stream)?; + stream.shutdown(Shutdown::Both)?; + } + + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn handle_conn_writes_response() { + let mut stream = [100u8].repeat(64_000); + let _ = handle_conn(&mut stream); + assert!(str::from_utf8(&stream).unwrap().contains("oh no")); + } }