Actix-web | 06 , Query Parameters

(Youtube Video)


use actix_web::{  get, web:: Query, App, HttpResponse, HttpServer, Responder };
use serde::Deserialize;


#[actix_web::main]
async fn main() {
    HttpServer::new( move ||  {
        App::new()
            .service(hello)
    })
        .bind("0.0.0.0:3000")
        .unwrap()
        .run()
        .await
        .unwrap()
}

#[get("/user")]
async fn hello(info : Query<Info>) -> impl Responder {
    let msg = format!("name: {}, age: {}", info.name, info.age);
    HttpResponse::Ok().body(msg)
}

#[derive(Deserialize)]
struct Info {
    name: String,
    age: i32
}

We define a handler , with path /user, then we add parameter to this handler ,whose type is Query , We define a struct type Info with attribute Deserialize from serde , put Info type in Query .

Then when we visit http://localhost:3000/user?name=jim&age=20 , it will show response : name: jim, age: 20