2 个版本

0.1.1 2024 年 5 月 14 日
0.1.0 2024 年 5 月 10 日

#896网络编程

Download history 112/week @ 2024-05-04 170/week @ 2024-05-11 28/week @ 2024-05-18 1/week @ 2024-05-25 1/week @ 2024-06-08

每月下载量 59 次

MIT/Apache

36KB
863

Monoio Route

用 Rust 编写的又一高性能路由库。

use monoio_route::Tree;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut router = Tree::new();
    router.insert(b"/home", "Welcome!")?;
    router.insert(b"/users/:id", "A User")?;
    router.insert(b"/message/:id", "A Message")?;
    router.insert(b"/:module/:id", "Other Module")?;
    router.insert(b"/*any", "Other Path")?;

    let (val, params) = router.at(b"/users/978").unwrap();
    assert_eq!(params.iter().find(|(k, _)| k == b"id").unwrap().1, b"978");
    assert_eq!(*val, "A User");

    let (val, params) = router.at(b"/some_module/978").unwrap();
    assert_eq!(params.iter().find(|(k, _)| k == b"id").unwrap().1, b"978");
    assert_eq!(params.iter().find(|(k, _)| k == b"module").unwrap().1, b"some_module");
    assert_eq!(*val, "Other Module");

    let (val, _) = router.at(b"/typo").unwrap();
    assert_eq!(*val, "Other Path");

    Ok(())
}

类似于知名的 matchit,但有所不同

  • 支持在同一路径上注册参数路由和捕获所有路由。
    • 匹配优先级:静态 > 参数 > 正则表达式 > 捕获所有
  • 支持正则表达式路由(未来将支持)。
  • 不支持裸参数或捕获所有。
  • 语法改为类似于 go httproute 的风格({param}->:param, {*any}->*any)。

依赖

~160–325KB