25个版本

0.5.6 2022年3月6日
0.5.5 2020年1月28日
0.5.3 2019年11月30日
0.5.1 2018年8月24日
0.3.5 2016年11月18日

#4#micro-framework

Download history 4/week @ 2024-07-02

每月 98 次下载

MIT 许可证

55KB
1K SLoC

Canteen

Build Status Latest Version

描述

Canteen是我用Rust实现的首个项目。它是我的最爱Python Web框架Flask的克隆。示例实现代码在canteen-impl仓库中。

用法

它并不完整,但我正在努力改进它,现在它已在crates.io上提供!要安装并查看,请将以下内容添加到您的Cargo.toml中

[dependencies]
canteen = "0.5"

Canteen的原则很简单——处理函数被定义为简单的Rust函数,这些函数接受一个Request并返回一个Response。然后,将这些处理函数附加到一个或多个路由和HTTP方法/动词上。路由使用简单的语法指定,允许您在路由中定义变量;然后可以从这些变量中提取信息以执行各种操作。目前,可以使用以下类型的变量

  • <str:name>将匹配路径段中的任何内容,并返回一个String
  • <int:name>将从一个路径段返回一个有符号整数(i32
    • 示例: cnt.add_route("/api/foo/<int:foo_id>", &[Method::Get], my_handler)将匹配"/api/foo/123"但不匹配"/api/foo/123.34""/api/foo/bar"
  • <uint:name>将返回一个无符号整数(u32
  • <float:name>int 参数定义做同样的事情,但匹配带小数点的数字,并返回一个 f32
  • <path:name> 会贪婪地获取所有包含的路径数据,返回一个 String
    • 例: cnt.add_route("/static/<path:name>", &[Method::Get], utils::static_file) 将以文件的形式提供 /static/ 目录下的任何内容

在处理程序附加到路由后,下一步就是简单地启动服务器。每当收到请求时,它都会与相关处理程序一起调度到线程池工作线程。工作线程在完成后通知父进程,然后将响应传回客户端。这很直接!

示例

extern crate canteen;

use canteen::*;
use canteen::utils;

fn hello_handler(req: &Request) -> Response {
    let mut res = Response::new();

    res.set_status(200);
    res.set_content_type("text/plain");
    res.append("Hello, world!");

    res
}

fn double_handler(req: &Request) -> Response {
    let to_dbl: i32 = req.get("to_dbl");

    /* simpler response generation syntax */
    utils::make_response(format!("{}", to_dbl * 2), "text/plain", 200)
}

fn main() {
    let cnt = Canteen::new();

    // bind to the listening address
    cnt.bind(("127.0.0.1", 8080));

    // set the default route handler to show a 404 message
    cnt.set_default(utils::err_404);

    // respond to requests to / with "Hello, world!"
    cnt.add_route("/", &[Method::Get], hello_handler);

    // pull a variable from the path and do something with it
    cnt.add_route("/double/<int:to_dbl>", &[Method::Get], double_handler);

    // serve raw files from the /static/ directory
    cnt.add_route("/static/<path:path>", &[Method::Get], utils::static_file);

    cnt.run();
}

依赖关系

~7.5–10MB
~184K SLoC