6 个版本
| 新增 0.2.0 | 2024 年 8 月 21 日 | 
|---|---|
| 0.1.4 | 2024 年 7 月 31 日 | 
#362 在 开发工具
576 每月下载量
20KB
52 行
更好的路由
better_routes 是一个 Rust 库,使在 axum 应用程序中进行路由变得轻而易举。使用易于使用的宏,您可以为类型创建路径并快速将方法链接到这些路径,从而使路由设置既简单又类型安全。
主要功能
- 集中式路由:
- 使用 routes!宏集中定义和管理所有路由。
- 通过将所有路由定义放在一个地方来简化路由配置。
 
- 使用 
- 类型化路径:
- 启用 typed-routing功能后,使用axum_extra::routing::TypedPath来类型化您的路径,确保类型安全和一致性。
- 直接从这些类型定义生成 URI。
 
- 启用 
- 方法处理器:
- method_helper宏为您类型化的路径生成- MethodHandler实现,将它们链接到相应的处理器,从而降低出错的风险。
- 使用方法注释轻松创建路由处理器。
 
安装
要安装 better-routes 和其他所需依赖项,请运行
cargo add better-routes
cargo add axum
cargo add axum-extra --features typed-routing
cargo add serde --features derive
使用方法
以下是一个简单的示例,演示如何使用 better_routes。
示例
use axum_extra::routing::RouterExt;
use axum_extra::routing::TypedPath;
use better_routes::method_helper;
use better_routes::routes;
use serde::Deserialize;
#[derive(Deserialize)]
struct Foo { 
    id : usize
}
#[derive(Deserialize)]
struct Bar;
// Define routes using the `routes!` macro.
// Note: `MethodHandlers` is required for typed path structs,
// and can be implemented using the `#[method_helper]` macro.
// Without this implementation, the `routes!` macro will panic.
routes! {
    name => pub AllRoutes, // Visibility is optional
    "/foo/:id" => Foo,
    "/bar" => Bar,
}
// Use the `method_helper` macro to implement `MethodHandlers`
// for the `Foo` struct.
#[method_helper]
impl Foo {
    #[get]
    #[allow(unused)]
    async fn foo(self) {
        println!("id: {}", self.id);
    }
}
// Use the `method_helper` macro to implement `MethodHandlers`
// for the `Bar` struct.
#[method_helper]
impl Bar {
    #[post]
    #[allow(unused)]
    async fn bar(self) {}
}
#[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();
}
说明
- routes!宏:将 URL 路径映射到用于路由处理的结构体,并支持类型安全的 URI 生成。
- method_helper宏:为带有- #[method_helper]的结构体实现- MethodHandler。
文档
有关状态和拒绝处理的高级使用方法,请参阅完整的 文档 或探索代码库中提供的其他 示例。
许可证
本项目采用 MIT 许可证。有关详细信息,请参阅 LICENSE 文件。
依赖关系
~6.5–8.5MB
~152K SLoC