#capture #iron #regex #router

rererouter

支持正则表达式捕获的 Iron 路由器

2 个版本

使用旧的 Rust 2015

0.1.1 2017 年 11 月 27 日
0.1.0 2017 年 11 月 26 日

HTTP 服务器 中排名第 1349

MIT 许可证

7KB
81

rererouter

Build Status

Iron 路由器支持 正则表达式 捕获。

用法

将以下内容添加到您的 Cargo.toml

[dependencies]
rererouter = "0.1"

并将以下内容添加到您的包根目录

extern crate rererouter;

示例

extern crate iron;
extern crate regex;
extern crate rererouter;

use regex::Captures;
use iron::prelude::{Iron};
use iron::{status, Request, Response};
use rererouter::RouterBuilder;

fn main() {
    let mut router_builder = RouterBuilder::new();

    router_builder.get(r"/hello-(?P<name>\w*)", |_: &mut Request, captures: Captures| {
        let greeting = format!("Hello, {}!", &captures["name"]);
        Ok(Response::with((status::Ok, greeting)))
    });

    router_builder.post(r"/count-to-(?P<count>\d*)", |_: &mut Request, captures: Captures| {
        let count = format!("Let's count to {}!", &captures["count"]);
        Ok(Response::with((status::Ok, count)))
    });

    router_builder.not_found(|_: &mut Request| {
        Ok(Response::with((status::NotFound, "Not found")))
    });

    let router = router_builder.finalize();
    Iron::new(router).http("localhost:3000").unwrap();
}

用法

$ curl -i https://127.0.0.1:3000/hello-rererouter

HTTP/1.1 200 OK
Content-Length: 18
Content-Type: text/plain
Date: Mon, 27 Nov 2017 08:36:47 GMT

Hello, rererouter!
$ curl -i -X POST https://127.0.0.1:3000/count-to-10

HTTP/1.1 200 OK
Content-Length: 18
Content-Type: text/plain
Date: Mon, 27 Nov 2017 08:37:19 GMT

Let's count to 10!
$ curl -i https://127.0.0.1:3000/not-found

HTTP/1.1 404 Not Found
Content-Length: 9
Content-Type: text/plain
Date: Mon, 27 Nov 2017 08:42:30 GMT

Not found

依赖项

~8MB
~184K SLoC