HFQR / xitca-web

Apache License 2.0
654 stars 41 forks source link

Named Parameters #1035

Closed andodeki closed 2 weeks ago

andodeki commented 3 weeks ago

How can i create a named parameter for the route as below:

pub fn routes(app: NestApp<Arc>) -> NestApp<Arc> { app.at("/", get(handler_service(|| async { NAME }))) .at("/get/:serial_number", get(handler_service(get_device))) } async fn getdevice( StateRef(state): StateRef<', Arc>, PathRef(serial_number): PathRef<'static>, ) -> Result<Json, StatusCode> { let devices = state.system.lock().unwrap(); if let Some(device) = devices.get(serial_number) { Ok(Json(device.clone())) } else { Err(StatusCode::NOT_FOUND) } }

fakeshadow commented 3 weeks ago

There are multiple ways to extract params from route path. For example:

use xitca_web::{
    error::Error,
    handler::{
        handler_service,
        params::{LazyParams, Params, ParamsRef},
    },
    route::get,
    App,
};

fn main() -> std::io::Result<()> {
    App::new()
        .at("/get/:serial_number", get(handler_service(handle)))
        .at("/get2/:serial_number", get(handler_service(handle2)))
        .at("/get3/:serial_number", get(handler_service(handle3)))
        .serve()
        .bind("0.0.0.0:8080")?
        .run()
        .wait()
}

// Params can be used to transform /: pattern to type implement serde::Deserialize traits.
async fn handle(Params(number): Params<String>) -> String {
    number
}

// type for zero copy deserialize params
#[derive(serde::Deserialize)]
struct SerialNumber<'a>(&'a str);

// LazyParams is lazy version of Params that can be used for zero copy deserialization.
async fn handle2(params: LazyParams<'_, SerialNumber<'_>>) -> Result<String, Error> {
    let SerialNumber(number) = params.deserialize()?;
    Ok(number.into())
}

// low level params where the route's param collection is exposed without typing.
async fn handle3(params: ParamsRef<'_>) -> String {
    params.get("serial_number").unwrap().into()
}

In general use Params first and explore other types when you have speci needs for them.