#axum #centralized #router #maintainable #typed-routing

better-routes

A powerful Rust library designed for generating type-safe and maintainable Axum routers

11 releases

0.3.4 Oct 3, 2024
0.3.3 Aug 29, 2024
0.2.0 Aug 21, 2024
0.1.4 Jul 31, 2024

#1248 in Web programming

Download history 409/week @ 2024-07-27 34/week @ 2024-08-03 3/week @ 2024-08-10 143/week @ 2024-08-17 531/week @ 2024-08-24 48/week @ 2024-08-31 1/week @ 2024-09-07 1/week @ 2024-09-14 7/week @ 2024-09-21 115/week @ 2024-09-28 29/week @ 2024-10-05 10/week @ 2024-10-12 2/week @ 2024-10-19 49/week @ 2024-11-02

63 downloads per month

MIT license

17KB

Better Routes

better_routes is a macro for centralizing all routes in an Axum application, making routing type-safe, maintainable, and less error-prone. It allows you to define routes, their handlers, and rejections in a single place, simplifying your application's routing logic.

Usage

Here’s a simple example demonstrating how to use better_routes.

Example

use axum_extra::routing::RouterExt;
use axum_extra::routing::TypedPath;
use better_routes::routes;
use serde::Deserialize;

#[derive(Deserialize)]
struct Foo {
    id: usize,
}

async fn foo(foo_path: Foo) {
    println!("id: {}", foo_path.id);
}

#[derive(Deserialize)]
struct Bar;

async fn bar(_: Bar) {}

// Define routes using the `routes!` macro.
routes! {
    name => pub AllRoutes, // Visibility is optional
    "/foo/:id" => Foo {
        get => foo
    },
    "/bar" => Bar {
        post => bar
    },
}

#[tokio::main]
async fn main() {
    // Use the router function generated by the `routes!` macro.
    let app = AllRoutes::routes();

    // Generate a URI from the `Foo` instance
    let foo_uri = Foo { id: 42 }.to_uri();
    println!("foo_uri: {}", foo_uri); // Output: foo_uri: /foo/42

    // Start the server
    let tcp_listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
        .await
        .unwrap();

    axum::serve(tcp_listener, app).await.unwrap();
}

Documentation

For more advanced usage, including state and rejection handling, please refer to the full documentation or explore additional examples provided in the codebase.

License

This project is licensed under the MIT License. See the LICENSE file for details.

Dependencies

~250–700KB
~17K SLoC