Closed andodeki closed 2 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.
How can i create a named parameter for the route as below: