Copy-pasteable code snippets for common Actix Web patterns: extractors, state injection, CORS, custom headers, and JSON error responders.
Standard production listener binding to all network interfaces on port 8080 with worker threads.
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new().service(index)
})
.workers(4)
.bind(("0.0.0.0", 8080))?
.run()
.await
}Type-safe extraction of URL path variables and query strings into Rust structs or HashMaps.
#[get("/users/{id}")]
async fn get_user(
path: web::Path<u64>,
query: web::Query<HashMap<String, String>>,
) -> impl Responder {
let user_id = path.into_inner();
format!("User ID: {}, Query: {:?}", user_id, query)
}Automatically parse incoming request application/json payloads into typed structs.
#[derive(Deserialize)]
struct CreateItem {
name: String,
price: f64,
}
#[post("/items")]
async fn create_item(body: web::Json<CreateItem>) -> impl Responder {
HttpResponse::Created().json(body.into_inner())
}Inject thread-safe database pools into application state using Arc-wrapped web::Data.
let pool = PgPoolOptions::new().connect(&db_url).await?;
HttpServer::new(move || {
App::new()
.app_data(web::Data::new(pool.clone()))
.service(handler)
})Attach access logging and permissive cross-origin resource sharing middleware.
use actix_cors::Cors;
use actix_web::middleware::Logger;
App::new()
.wrap(Logger::default())
.wrap(Cors::permissive())Standardized JSON error envelope helper functions.
#[derive(Serialize)]
struct ErrorEnvelope {
error: String,
code: u16,
}
fn bad_request_error(msg: &str) -> HttpResponse {
HttpResponse::BadRequest().json(ErrorEnvelope {
error: msg.to_string(),
code: 400,
})
}Get complete downloadable SaaS repositories with SQLx, JWT auth, Stripe billing, and Distroless Docker files.