G2's Blog

A Very Small HTTP Server

August 8, 2024

After my previous adventures with image formats, I've not been doing much programming. Last night however, I decided to try making a very simple HTTP server using Rust with just the standard library. Despite not knowing exactly how HTTP requests worked, I supposed it couldn't be that difficult, and I was right!

I got it working (responding to requests, etc.) in around 40 lines of normal Rust code, which made me think... how small could I make it? The answer, without putting everything on one line and keeping to normal(ish) style, was 8 lines.

Here's the whole program:

fn main() {
    for mut stream in std::net::TcpListener::bind("0.0.0.0:8950").unwrap().incoming().map(|i| i.unwrap()) {
        let _ = std::io::Read::bytes(std::io::Read::by_ref(&mut stream)).try_fold(Vec::new(), |mut a: Vec<u8>, b| {
            a.push(b.unwrap());
            if a.ends_with(b"\r\n\r\n") {Err(a)} else {Ok(a)} // We actually use the error as the result...
        }).inspect_err(|_| std::io::Write::write_all(&mut stream, b"HTTP/1.1 200 Success\r\nContent-Type: text/html\r\n\r\nThis is a website I guess\n").unwrap())
    }
}

That's all. Not much to report here!

Comments