4个版本
使用旧的Rust 2015
0.2.0 | 2016年10月30日 |
---|---|
0.1.2 | 2016年10月29日 |
0.1.1 | 2016年10月29日 |
0.1.0 | 2016年10月29日 |
#1138 in HTTP服务器
每月 23 次下载
8KB
212 行
route-rs
这个crate是我尝试为Rust Web应用程序创建一个安全助手,用于将URL路由映射到处理器。
已经有几个路由库可用,但我能找到的所有的都存在一个共同问题:路径模式定义为字符串,URL参数在运行时解析并存储在处理器必须使用 Map
的 .get()
和 .unwrap()
方法来访问的某种映射中。我想在不解包的情况下提取参数,并且我想让Rust的类型系统确保我不会犯错误!
配置
在Cargo.toml中
[dependencies]
route = "0.2.0"
route
仅导出宏 route!
,因此您需要 #[macro use]
它
#[macro use]
extern crate route;
用法
假设您已经设置了一些HTTP请求/响应服务器
// imaginary request/response structs provided by the framework:
struct Request<'a> {
path: &'a str,
}
type Response = String;
// application handlers that we need to route:
// Note that some handlers take extra parameters that we hope to fill from the path!
fn home(req: &Request) -> Response {
"home".to_string()
}
fn blog_post(req: &Request, id: u32) -> Response {
format!("blog: {}", id)
}
fn account(req: &Request, subpath: &str) -> Response {
format!("account -- subpath: {}", subpath)
}
然后您可以设置一个路由处理器,如下所示
fn handle_route(req: &Request) -> Response {
route!(req.path, {
(/) => home(req);
(/"blog"/[id: u32]) => blog_post(req, id);
(/"me"[/rest..]) => account(req, rest);
});
Response::from("not found")
}
这样您就设置好了!
assert_eq!(&handle_route(&Request { path: "/" }), "home");
assert_eq!(&handle_route(&Request { path: "/blog/42" }), "blog: 42");
assert_eq!(&handle_route(&Request { path: "/me/a/b/c" }), "account -- subpath: /a/b/c");
assert_eq!(&handle_route(&Request { path: "/foo" }), "not found");