Skip to main content

Crate axum_controller

Crate axum_controller 

Source
Expand description

Crates.io Documentation Maintenance unsafe forbidden

§Axum-Controller

Helper macros for wiring up axum routes with less boilerplate.

This crate is an extension of axum-typed-routing. It uses the #[route] attribute and TypedRouter trait from that crate. You must add axum-typed-routing to your own Cargo.toml dependencies.

See example here.

See the docs for more information.

§Licensing

This repository, is licensed under the GNU Affero General Public License v3.0 or later (AGPL-3.0-or-later). This ensures that modifications to the code remain open source when used in network services.

§Inspiration & Influences

This crate is inspired by and uses/used axum-typed-routing & route_controller .

This crate is an extension of [axum_typed_routing]. It uses the #[route] attribute and the TypedRouter trait from that crate to discover and wire up handler methods. You must add axum-typed-routing to your own Cargo.toml dependencies for this crate to work.

§Route macro usage

See the docs of [axum_typed_routing] for details on the #[route] macro.

§Controller macro usage

This crate offers the controller() attribute macro. use it like this:

use axum::extract::State;
use axum_controller::controller;

use axum_typed_routing::route;
use axum_typed_routing::TypedRouter;

async fn my_middleware(
    request: axum::extract::Request,
    next: axum::middleware::Next,
) -> axum::response::Response {
    next.run(request).await
}

async fn my_other_middleware(
    request: axum::extract::Request,
    next: axum::middleware::Next,
) -> axum::response::Response {
    next.run(request).await
}

#[derive(Clone, Debug)]
struct AppState();

struct ExampleController;

#[controller(
    path = "/asd",
    state = AppState,
    middleware=axum::middleware::from_fn(my_middleware),
    middleware=axum::middleware::from_fn(my_other_middleware),
)]
impl ExampleController {
    #[route(GET "/test")]
    async fn test_handler_fn(_: State<AppState>) -> String {
        todo!("handle request")
    }

    #[route(GET "/test2")]
    async fn test_handler_fn2(State(_): State<AppState>) -> String {
        todo!("handle request")
    }
}

fn main() {
    let _router_a: axum::Router<AppState> = ExampleController::into_router();
    let _router_b: axum::Router<()> = ExampleController::into_app_router(AppState());
}

Attribute Macros§

controller
A macro that generates into_router and into_app_router methods which automatically wire up all #[route] handlers and the given middlewares, path-prefix etc.