|
|||||
Actix webでWebアプリケーションを書くRustでWebアプリケーションを書くにはActix web等のクレートを使うのが手軽そうだ。同様のものでRocketもあるが、こちらはNightlyのRustを使う必要があるそうなので、Actix webを選択した。 まずはパッケージを作成する。 $ cargo new hello-actix-web Cargo.tomlに依存関係を追加する。 [dependencies] actix-web = "3" 次に、src/main.rsに以下のコードを書く。ポートはHttpServerのbindで指定できる。
use actix_web::{get, App, HttpResponse, HttpServer, Responder};
#[get("/")]
async fn index() -> impl Responder {
HttpResponse::Ok().body("Hello, world !")
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| App::new().service(index))
// localhostからのみアクセスするなら127.0.0.1
.bind("127.0.0.1:8080")?
.run()
.await
}
これをcargo runコマンドで実行すると、依存するクレート等必要なものがダウンロード、ビルドされた後、Webサーバが8080ポートで起動する。
$ cargo run
Finished dev [unoptimized + debuginfo] target(s) in 0.55s
Running `target/debug/hello-actix-web`
例えば、起動したサーバにcurlでアクセスすれば結果が返される。もちろん、普通にブラウザからアクセスしても良い。 $ curl http://localhost:8080/ Hello, world ! もし、このサーバをEC2等で動かして外部からのリクエストも処理したいなら、bindするアドレスを"0.0.0.0"にすれば良いようだ。
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| App::new().service(index))
// EC2等に配置して外部からアクセスするなら0.0.0.0
.bind("0.0.0.0:8080")?
.run()
.await
}
(2021/01/08)
Copyright© 2004-2021 モバイル開発系(K) All rights reserved.
[Home]
|
|||||