【Rust】Actix WebでHello world

投稿日: 更新日:

環境

OS: Ubuntu 20.04.4 LTS (WSL2) rustc: 1.63.0

Hello world

プロジェクトを作成する

cargoでプロジェクトを作成します。作成したディレクトリ内に移動してください。

$ cargo new hello-world
$ cd hello-world

Cargo.tomlの編集

Cargo.toml[dependencies]の下にactix-web = "4"と書いてください。

[dependencies]
actix-web = "4"

コードを書く

以下のコードをmain.rsに書いてください。

use actix_web::{get, post, web, App, HttpResponse, HttpServer, Responder};

#[get("/")]
async fn hello() -> impl Responder {
    HttpResponse::Ok().body("Hello world!")
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new()
            .service(hello)
    })
    .bind(("127.0.0.1", 8080))?
    .run()
    .await
}

hello関数がHello world!と表示させる部分です。

実行する

以下のコマンドで実行できます。

$ cargo run

http://127.0.0.1:8080/ へアクセスすればHello world!と表示されるはずです。

出来たら他の文字列に変えて試してみてください。

書いた人

profile_image

お茶の葉

物理とプログラミングが好きな人