Skip to main content

mount_handlers

Macro mount_handlers 

Source
macro_rules! mount_handlers {
    ($controller:ty, $state:ty, [ $( ($route:expr, $handler:expr) ),* $(,)? ]) => { ... };
}
Expand description

Generate a Controller implementation for a type from a handler list.

This macro produces the Kleisli arrow Arc<State> -> (Router -> Result<Router>) that the RouterPipeline::mount method threads through the pipeline.

Controllers using this macro have zero dependency on Router, RouteSet, or any DI container in their source files.

§Syntax

mount_handlers!(ControllerType, ServiceType, [
    (__route_constant_1, handler_fn_1),
    (__route_constant_2, handler_fn_2),
]);

Where each __route_constant is the tuple (&'static str, &'static str) generated by a #[get]/#[post]/etc. annotation on the handler function.

§Example

pub struct HealthController;

#[get("/health")]
pub async fn health_check(State(svc): State<Arc<HealthService>>) -> Json<HealthResponse> {
    Json(svc.health_check())
}

mount_handlers!(HealthController, HealthService, [
    (__health_check_route, health_check),
]);

Then in main.rs:

RouterPipeline::new()
    .mount::<HealthController>(Arc::new(HealthService::new()))
    .build()?