rustup updateを実行して、Rust の最新バージョンを利用可。
※本チュートリアルでは、Rust 1.54 以降を使用していることを前提にしています。
まず、バイナリベースの新しい Cargo プロジェクトを作成し、新しいディレクトリに移動します。
cargo new hello-world cd hello-world
Cargo.toml ファイルに以下を追加して、actix-web をプロジェクトの依存関係として追加します。
[dependencies] actix-web = "4"
リクエストハンドラは、ゼロ個以上のパラメータを受け取る非同期関数を使用します。これらのパラメータは、リクエストから抽出され(FromRequest)、HttpResponse に変換可能な型を返します(Responder)。
use actix_web::{get, post, web, App, HttpResponse, HttpServer, Responder};
#[get("/")]
async fn hello() -> impl Responder {
HttpResponse::Ok().body("Hello world!")
}
#[post("/echo")]
async fn echo(req_body: String) -> impl Responder {
HttpResponse::Ok().body(req_body)
}
async fn manual_hello() -> impl Responder {
HttpResponse::Ok().body("Hey there!")
}
これらのハンドラのいくつかは、組み込みのマクロを使用して直接ルーティング情報を付加していることに注意してください。これらは、ハンドラが応答すべきメソッドとパスを指定するためのものです。
次に、App のインスタンスを作成し、リクエストハンドラを登録します。ルーティングマクロを使うハンドラには App::service を、手動でルーティングするハンドラには App::route を使用し、パスとメソッドを宣言します。最後に、アプリは HttpServer 内で起動され、アプリを「アプリケーションファクトリ」として使用して、入ってくるリクエストに対応します。
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new()
.service(hello)
.service(echo)
.route("/hey", web::get().to(manual_hello))
})
.bind(("127.0.0.1", 8080))?
.run()
.await
}
以上です。
cargo run でコンパイル&実行します。
[actix_web::main] マクロは、actix ランタイム内で非同期 main 関数を実行します。
http://127.0.0.1:8080/ もしくはリクエストハンドラで定義した他のルートにアクセスして、結果を確認することができます。
