Trait gotham::extractor::PathExtractor
source · pub trait PathExtractor<B>: for<'de> Deserialize<'de> + StaticResponseExtender<ResBody = B> + StateDatawhere
B: HttpBody,{ }
Expand description
Defines a binding for storing the dynamic segments of the Request
path in State
. On failure
the StaticResponseExtender
implementation extends the Response
to indicate why the
extraction process failed.
This trait is automatically implemented when the struct implements the Deserialize
,
StateData
and StaticResponseExtender
traits. These traits can be derived, or implemented
manually for greater control.
The default behaviour given by deriving all three traits will use the automatically derived
behaviour from Serde, and result in a 400 Bad Request
HTTP response if the path segments are
not able to be deserialized.
Examples
#[derive(Deserialize, StateData, StaticResponseExtender)]
struct MyPathParams {
id: i32,
slug: String,
}
fn handler(mut state: State) -> (State, Response<Body>) {
let MyPathParams { id, slug } = MyPathParams::take_from(&mut state);
let body = format!("id = {}, slug = {}", id, slug);
let response = create_response(
&state,
StatusCode::OK,
mime::TEXT_PLAIN,
body,
);
(state, response)
}
fn router() -> Router {
build_simple_router(|route| {
route
.get("/article/:id/:slug")
.with_path_extractor::<MyPathParams>()
.to(handler);
})
}