Programming / 3 min read
Build a tiny web server in Rust
Run a small Rust server and use curl to see what it sends to your browser.
What does a browser get back when it asks for a page? You can see the answer by running a tiny Rust server on your own computer. It sends two words: Hello, Rust!
Make a new project
Open a terminal and make a new Rust project. This example uses the tools that come with Rust. You won’t need to add any packages.
cargo new tiny-server
cd tiny-server
Replace the code in the main file with the example below.
use std::io::{self, BufRead, BufReader, Read, Write};
use std::net::{TcpListener, TcpStream};
use std::time::Duration;
fn reply(mut stream: TcpStream) -> io::Result<()> {
let timeout = Some(Duration::from_secs(2));
stream.set_read_timeout(timeout)?;
stream.set_write_timeout(timeout)?;
let mut line = String::new();
let bytes = BufReader::new((&mut stream).take(4096)).read_line(&mut line)?;
if bytes == 0 || !line.ends_with('\n') {
return Ok(());
}
let body = "Hello, Rust!";
write!(
stream,
"HTTP/1.1 200 OK\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{}",
body.len(),
body
)
}
fn main() -> io::Result<()> {
let listener = TcpListener::bind("127.0.0.1:7878")?;
println!("Open http://127.0.0.1:7878 in your browser.");
for stream in listener.incoming() {
if let Err(err) = stream.and_then(reply) {
eprintln!("{err}");
}
}
Ok(())
}
Then run it and open the local address in your browser.
cargo run
The address only works on your own computer. To stop the server, press Ctrl+C in the first terminal.
Look at the HTTP reply
curl -i http://127.0.0.1:7878/
Here’s what the browser gets back. The first line says the request worked. The next two lines tell the browser what kind of text to expect and how many bytes to read. A blank line marks the end of those details. The text after that line is what you see on the page.
HTTP/1.1 200 OK
Content-Type: text/plain; charset=utf-8
Content-Length: 12
Connection: close
Hello, Rust!
Give it a second page
Try asking for a made-up path. You’ll still see the same words. This server reads the first line of the request, but it doesn’t use the path to pick a reply. To add a second page, start by checking that path. Save this version as a small test you can come back to when your changes break.
Further reading: The Rust Book: Building a Single-Threaded Web Server.