title: Actix Web Server 01 tags: rust actix net web server ```toml [package] name = "actix1" version = "0.1.0" edition = "2021" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] actix-web = "4.0" ``` ```rust use actix_web::{web, App, HttpServer, Responder}; async fn index() -> impl Responder { "Hello, Actix Web Server!" } #[actix_web::main] async fn main() -> std::io::Result<()> { // Start the HTTP server HttpServer::new(|| { App::new().route("/", web::get().to(index)) }) .bind("127.0.0.1:3000")? .run() .await } ``` ## Simple Route Examples ```rust use actix_web::{web, App, HttpServer, HttpRequest, HttpResponse, Responder}; // Aim: // Add an /a/etc route // that prints out the path async fn index(req: HttpRequest) -> impl Responder { let full_path = req.uri().path(); format!("Hello, Actix Web Server! {}",full_path) } async fn route_a(req: HttpRequest) -> HttpResponse { let full_path = req.uri().path(); HttpResponse::Ok().body(format!("Received A path: {}",full_path)) } async fn route_b(req: HttpRequest) -> HttpResponse { let full_path = req.uri().path(); HttpResponse::Ok().body(format!("Path B path: {}",full_path)) } async fn route_c(path: web::Path<(String,)>) -> HttpResponse { let captured_path = &path.0; HttpResponse::Ok().body(format!("Wildcard C path: {}",captured_path)) } #[actix_web::main] async fn main() -> std::io::Result<()> { // Start the HTTP server let port = 3000; let host = format!("0.0.0.0:{}",&port); println!("Serving on {}",&host); HttpServer::new(|| { App::new().route("/", web::get().to(index)) .route("/a/{tail:.*}", web::get().to(route_a)) .route("/b/{path}", web::get().to(route_b)) .route("/c/{tail:.*}", web::get().to(route_c)) }) .bind(&host)? .run() .await } ``` Then A and C will capture the whole path (this is what `{tail:.*}` does. See [the docs](https://actix.rs/docs/url-dispatch/). Whereas B will only capture `/b/hello` and not `/b/hello/world` (the latter generates a 404). ## Using #[get()] ```rust use actix_web::{get, web, App, HttpServer, HttpRequest, HttpResponse, Responder}; #[get("/d/{tail:.*}")] async fn route_d(path: web::Path<(String,)>) -> HttpResponse { let path = &path.0; HttpResponse::Ok().body(format!("Path D: {}",path)) } #[actix_web::main] async fn main() -> std::io::Result<()> { // Start the HTTP server HttpServer::new(|| { App::new().service(route_d) }) .bind("127.0.0.1:3000")? .run() .await } ```