Now that you have completed the "Advanced Rust" book, a great final milestone project could be building a web server using Rust.
This project would combine many advanced concepts you've learned throughout the book, including concurrency, error handling, macros, and more.
Note: You must build the web server without any frameworks — just vanilla Rust — because it will help you understand the code abstracted by the frameworks you will use later. Furthermore, it will enforce your understanding of what is happening under the hood in an HTTP client-server communication. Here’s a simple scaffold you can iterate from:
use std::io::{Read, Write};
use std::net::{TcpListener, TcpStream};
use std::thread;
fn handle_client(mut stream: TcpStream) {
let mut buffer = [0; 1024];
stream.read(&mut buffer).unwrap();
let response = "HTTP/1.1 200 OK\\r\\n\\r\\nHello, Rust Web Server!";
stream.write(response.as_bytes()).unwrap();
stream.flush().unwrap();
}
fn main() {
let listener = TcpListener::bind("127.0.0.1:8080").expect("Failed to bind port");
println!("Listening on <http://127.0.0.1:8080>");
for stream in listener.incoming() {
match stream {
Ok(stream) => {
thread::spawn(|| {
handle_client(stream);
});
}
Err(e) => {
eprintln!("Error: {}", e);
}
}
}
}
When you run Cargo, you should see the prompt message. Then, visit port 8080 in the browser, or use curl:
In this example, we create a basic single-threaded web server that listens on 127.0.0.1:8080
. When a client connects, a new thread is spawned to handle the client's request.
The handle_client
function reads the incoming HTTP request, sends a simple HTTP response, and flushes the stream.
Please note that this example is minimal and lacks many features of a fully-fledged web server. For production use, you must consider factors like handling different HTTP methods, routing, error handling, security, performance optimization, and more.
Furthermore, you may be able to build your own Rust web framework from scratch someday! For now, iterate over this project by following the following steps.
Final words
Congratulations on completing this journey into the Rust ecosystem and toolchain. You have learned quite a lot; if you are reading this, you probably have done quite a lot with Rust.
This aspect of rust is as deep as it gets, but there are still concepts in the language that you would figure out when you need to. The foundations you have built with this journey will be enough to understand anything that comes your way and build powerful systems that scale performantly.
If you follow the exercises in this book. That means you should be able to build your tools from scratch in your systems, from caching to databases.