How does axum actually wire routes and handlers? #1438
-
Hi, new to web-dev, just started exploring question: I understand that a In the example below, I have 2 handlers let app = Router::new()
.route("/hello/:name", get(json_hello));
.route("/bye/:name", get(json_bye));
async fn json_hello(Path(name): Path<String>) -> impl IntoResponse {
let greeting = name.as_str();
let hello = String::from("Hello ");
(StatusCode::OK, Json(json!({ "message": hello + greeting })))
}
async fn json_bye(Path(name): Path<String>) -> impl IntoResponse {
let farewell = name.as_str();
let hello = String::from("Bye ");
(StatusCode::OK, Json(json!({ "message": hello + farewell })))
} and #[allow(non_snake_case)]
impl<F, Fut, B, Res, T1, T2> Handler<(T1, T2), B> for F
where
F: FnOnce(T1, T2) -> Fut + Clone + Send + 'static,
Fut: Future<Output = Res> + Send,
B: Send + 'static,
Res: IntoResponse,
T1: FromRequest<B> + Send,
T2: FromRequest<B> + Send,
{
type Future = Pin<Box<dyn Future<Output = Response> + Send>>;
fn call(self, req: Request<B>) -> Self::Future {
Box::pin(async move {
let mut req = RequestParts::new(req);
let T1 = match T1::from_request(&mut req).await {
Ok(value) => value,
Err(rejection) => return rejection.into_response(),
};
let T2 = match T2::from_request(&mut req).await {
Ok(value) => value,
Err(rejection) => return rejection.into_response(),
};
let res = self(T1, T2).await;
res.into_response()
})
}
} So, any help in clearing this up would be great. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 5 replies
-
Great question! I'm gonna talk about how it works in 0.6, things work similarly in 0.5.
Hopefully that makes things a bit more clear 😊 You're welcome to ask more questions. |
Beta Was this translation helpful? Give feedback.
Great question!
I'm gonna talk about how it works in 0.6, things work similarly in 0.5.
Router::route
takes a path and aMethodRouter
.MethodRouter
is is constructed via something likeaxum::routing::get
.get
,post
, etc are all the same so they're defined in a macro here.axum::routing::on
which callsMethodRouter::on
MethodRouter::on_service
but requires a service. Previously we've only received aH: Handler<T, S, B>
. How theHandler
trait works is a different question and somewhat orthogonal.Handler
into aService
withIntoServiceStateInExtension
. That is why you never seeHandler::call
being called. Because we call it viaIntoServiceStateIn…