Rust Web Frameworks
Rust web frameworks provide different approaches to building web applications while maintaining Rust's safety guarantees. This tutorial examines the three most popular options.
1. Framework Installation
Each framework has distinct setup requirements:
Actix Web Setup
# Cargo.toml
[dependencies]
actix-web = "4"
actix-rt = "2"
use actix_web::{get, App, HttpServer, Responder};
#[get("/")]
async fn hello() -> impl Responder {
"Hello Actix!"
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new().service(hello)
})
.bind(("127.0.0.1", 8080))?
.run()
.await
}
2. Rocket Framework
Rocket focuses on developer convenience:
Rocket Setup
# Cargo.toml
[dependencies]
rocket = "0.5.0-rc.2"
#[macro_use] extern crate rocket;
#[get("/")]
fn index() -> &'static str {
"Hello Rocket!"
}
#[launch]
fn rocket() -> _ {
rocket::build().mount("/", routes![index])
}
3. Axum Framework
Axum integrates with Tokio ecosystem:
Axum Setup
# Cargo.toml
[dependencies]
axum = "0.6"
tokio = { version = "1.0", features = ["full"] }
use axum::{Router, routing::get};
async fn hello() -> &'static str {
"Hello Axum!"
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(hello));
axum::Server::bind(&"0.0.0.0:3000".parse().unwrap())
.serve(app.into_make_service())
.await
.unwrap();
}
4. Handling Requests
Path parameter examples:
Actix Web
#[get("/users/{id}")]
async fn get_user(id: web::Path) -> impl Responder {
format!("User {}", id)
}
Rocket
#[get("/users/<id>")]
fn get_user(id: u32) -> String {
format!("User {}", id)
}
Axum
async fn get_user(
axum::extract::Path(id): axum::extract::Path<u32>
) -> String {
format!("User {}", id)
}
5. Error Responses
Framework-specific error handling:
Actix Web
use actix_web::error::ResponseError;
impl ResponseError for MyError {
fn error_response(&self) -> HttpResponse {
HttpResponse::BadRequest().json("Failed")
}
}
Rocket
#[catch(404)]
fn not_found() -> &'static str {
"Resource not found"
}
Axum
async fn handler() -> Result<&'static str, StatusCode> {
Err(StatusCode::NOT_FOUND)
}
×