4 个版本

0.1.3 2019年11月10日
0.1.2 2019年11月9日
0.1.1 2019年11月9日
0.1.0 2019年11月9日

#11 in #http-router

MIT 许可协议

66KB
456

Crates.io Documentation

HTTP Tools

http_tools crate 旨在为 http crate 中找到的类型提供额外的功能。这个 crate 旨在只提供不引起堆分配的函数,并尽可能地轻量。此外,该 crate 与任何也使用 http crate 的库或 web 框架兼容。

过滤器

该 crate 提供了在 http crate 中找到的 Request 和 Response 类型的工具,允许快速创建一个 http 路由器。

use http_tools::request::{Extension, Filter};

// standard Http::request::Request
request
    // Creates an Option<&Request>, each fiter returns Some(req) if it passes and None if it fails
    .filter()
    // match the path /item/{} where {} is a wild card
    .filter_path("/item/{}")
    // request has the method of type POST
    .filter_method("POST")
    // The header has the key content-type with a value of application/x-www-form-urlencoded
    .filter_header("content-type", "application/x-www-form-urlencoded")
    // The {} wild card can be used to filter headers aswell
    .filter_header("content-length", "{}")
    // The query has the key cool with the value rust
    .filter_query("cool", "rust")
    // the wild card {} can be used in queries, filters do not decode uri encodings
    .filter_query("also+cool", "{}")
    // custom filters can be applied, and will be given the request and return a bool
    .filter_custom(|req| req.extensions().get::<i32>().is_some())
    // The request has a scheme of https
    .filter_scheme("https")
    // filters simply return std Option where Some means pass and None means failed
    .and_then(|_request| Some("I passed the test!"));

路由服务

该 crate 提供了一些有用的宏,以减少创建路由服务时的样板代码。

#[macro_use] extern crate http_tools;
use http_tools::request::{Extension, Filter};
use http::request::{Request};
use http::response::{Builder, Response};

// routes the request to the proper handler and returns the response
fn router(req : &Request<()>) -> Response<()> {
    // Handles Post requests to root uri
    handle_fn!(post_handler, req.filter()
        .filter_path("/")
        .filter_method("POST"));

    // Handles Get requests to root uri
    handle_fn!(get_handler, req.filter()
        .filter_path("/")
        .filter_method("GET"));

    // Handles Get requests to some_service/WILDCARD 
    handle_fn!(service_handler, req.filter()
        .filter_path("some_service/{}")
        .filter_method("GET"));

    // Returns method not found
    Builder::new().status(405).body(()).unwrap()
}

迭代器

该 crate 提供了一些有用的迭代器。

use http_tools::request::query_iter;

// use the http_tools function to create an iterator given an http::request::Request
for (key, value) in query_iter(&request){
    println!("{} {}", key, value)
}

依赖项

~1MB
~14K SLoC