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 ( ) ;
}