rust canteen
1.0.0
食堂は、私が錆で実装している最初のプロジェクトです。私のお気に入りのPython WebフレームワークであるFlaskのクローンです。 Canteen-IMPLリポジトリに実装の例のコードがあります。
それは決して完全ではありませんが、私はそれに取り組んでおり、現在はcrates.ioで入手可能です!インストールしてチェックアウトするには、以下を貨物に追加します。toml:
[ dependencies ]
canteen = " 0.5 "食堂の背後にある原則は単純です - ハンドラー関数は、 Requestを取り、 Responseを返す単純な錆関数として定義されます。ハンドラーは、1つ以上のルートと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> unsigned Integer( 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 ( ) ;
}