Dup Ver Goto 📝

Actix Web Server 01

To
98 lines, 275 words, 2614 chars Page 'ActixServer_01' does not exist.
[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"
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

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. Whereas B will only capture /b/hello and not /b/hello/world (the latter generates a 404).

Using #[get()]

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
}