6个版本
0.7.0 | 2019年9月16日 |
---|---|
0.6.5 | 2019年8月6日 |
0.6.3 | 2018年11月21日 |
#216 in #router
9KB
172 行
reset-router
一个基于RegexSet
的快速路由器,用于异步Hyper (0.12)。
提供基于属性的可选路由,使用proc_macro_attribute
。启用with-macros
特性标志以使用此功能。
单独的处理函数应该具有类型H
,其中
H: Fn(http::Request<Body>) -> I + Sync + Send + 'static,
I: IntoFuture<Item = S, Error = E>,
I::Future: 'static + Send,
S: Into<http::Response<Body>>,
E: Into<http::Response<Body>>,
您可以返回一些非常简单的东西,如Ok(Response::new())
。除非您需要读取请求正文或与其他未来感知事物交互,否则无需担心futures。
用法
extern crate futures;
extern crate http;
extern crate hyper;
extern crate reset_router;
use futures::{Future};
use reset_router::{bits::Method, Request, Response, Router, RequestExtensions};
#[derive(Clone)]
pub struct State(pub i32);
fn hello(req: Request) -> Result<Response, Response> {
let (first_name, last_name) = req.parsed_captures::<(String, String)>()?;
Ok(http::Response::builder()
.status(200)
.body(format!("Hello, {} {}!", first_name, last_name).into())
.unwrap())
}
fn unreliable_add(req: Request) -> Result<Response, Response> {
let (add1, add2) = req.parsed_captures::<(i32, i32)>()?;
let state_num: i32 = req.state::<State>().map(|x| x.0 ).unwrap_or(0);
Ok(http::Response::builder()
.status(200)
.body(format!("{} + {} = {}\r\n", add1, add2, add1 + add2 + state_num).into())
.unwrap())
}
fn main() {
let router = Router::build()
.with_state(State(42))
.add(Method::GET | Method::POST, r"^/hello/([^/]+)/(.+)$", hello)
.add(http::Method::GET, r"^/add/([\d]+)/([\d]+)$", unreliable_add)
.finish()
.unwrap();
let addr = "0.0.0.0:3000".parse().unwrap();
let server =
hyper::Server::bind(&addr).serve(router).map_err(|e| eprintln!("server error: {}", e));
hyper::rt::run(server);
}
或者使用基于属性的路由
extern crate futures;
extern crate http;
extern crate hyper;
#[macro_use]
extern crate reset_router;
use futures::Future;
use reset_router::Router;
#[derive(Clone, Debug)]
pub struct State {
pub goodbye: String,
}
pub mod handlers {
use super::State;
use reset_router::{Request, Response, RequestExtensions};
#[route(path = "^/goodbye$", methods = "GET, POST")]
pub fn goodbye(req: Request) -> Result<Response, Response> {
let state = req.state::<State>().unwrap();
Ok(http::Response::builder().status(200).body(state.goodbye.clone().into()).unwrap())
}
#[get(r"^/hello/([^/]+)/(\d+)$")]
pub fn hello(req: Request) -> Result<Response, Response> {
let (name, age) = req.parsed_captures::<(String, u8)>()?;
Ok(http::Response::builder()
.status(200)
.body(format!("Hello, {} year old named {}!", age, name).into())
.unwrap())
}
}
fn main() {
let router = Router::build()
.with_state(State { goodbye: "Goodbye".into() })
.add_routes(routes![handlers::hello, handlers::goodbye])
.finish()
.unwrap();
let addr = "0.0.0.0:3000".parse().unwrap();
let server =
hyper::Server::bind(&addr).serve(router).map_err(|e| eprintln!("server error: {}", e));
hyper::rt::run(server);
}
当前版本:0.6.5
许可证:MIT
依赖项
~2MB
~46K SLoC