rust canteen
1.0.0
食堂是我在Rust中实施的第一个项目。这是我最喜欢的python网络框架的烧瓶的克隆。在食堂IMPL存储库中有一个示例实现的代码。
这绝不是完整的,但是我正在努力,现在可以在Crates.io上使用!要安装并检查出来,请将以下内容添加到您的cargo.toml:
[ dependencies ]
canteen = " 0.5 "食堂背后的原理很简单 - 处理程序功能被定义为简单的锈函数,该函数接受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>将贪婪地获取包含的所有路径数据,返回Stringcnt.add_route("/static/<path:name>", &[Method::Get], utils::static_file)将在/static/ directory中使用任何内容将处理程序连接到路由后,下一步就是简单地启动服务器。每当收到请求时,都会将相关处理程序派往ThreadPool Worker。工人在完成后通知父程进程,然后将响应发送给客户端。非常简单的东西!
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 ( ) ;
}