LoginSignup
7
0

More than 1 year has passed since last update.

Rust勉強のために actix-web で Hello world!

Last updated at Posted at 2022-12-18

この記事は、 Qiita株式会社のカレンダー | Advent Calendar 2022 - Qiita の 18 日目の記事です。

はじめに

Rustを勉強するため慣れ親しんだWebアプリを作成してRustと親睦を深めることを目的にしています
この記事では簡単に Hollow World を表示までやっていきます

Rust のセットアップ

Rust のセットアップに関してはこちらの記事を参考にセットアップした
こちらの記事では割愛させていただきます

今回Webフレームワークとして actix-web を利用していきます

プロジェクトのセットアップ

まずプロジェクトのためのディレクトリを作成します

$ mkdir ./hello_world
$ cd hello_world

次にプロジェクトの初期化を行います
cargo を使っていきます
cargo はRustのビルドシステム兼パッケージマネージャです

$ cargo init
$ tree
.
├── Cargo.toml
└── src
    └── main.rs

ファイルは見ての通り2つ作られます
Cargo.toml がプロジェクトの設定ファイルです
dependencies 以下に必要なパッケージを記載します

Cargo.toml
[package]
name = "hello_world"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]

もう一つのsrc以下のディレクトリに実行ファイルを置くことを期待されています
ここではデフォルトで作成された main.rs を見てみる

src/main.rs
fn main() {
    println!("Hello, world!");
}

Hello, world! を表示するプログラムになっていることが察せる

では動かしてみる
cargo run を実行することでコンパイルされてmain.rsが実行される


$ cargo run
   Compiling hello_world v0.1.0 (/hello_world)
    Finished dev [unoptimized + debuginfo] target(s) in 1.18s
     Running `target/debug/hello_world`
Hello, world!

actix-web のセットアップ

ここからは実際にセットアップしていきます
Cargo.toml に今回使う actix-web を追加する
[dependencies]セクションにプロジェクトに必要な依存関係を追記することができます

[package]
name = "hello_world"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
+ actix-web = "4"

actix-web のセットアップはこれだけです
ではHollow Worldを表示するように main.rs を修正していきます

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

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

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

簡単なコードですが一応コードを見ていきます
main() では Appインスタンスを作成して hello をルーディングとして設定しています
またHttpServer127.0.0.1:8080 を指定して起動しています

hello() は http status を 200番を指定してHello world!を表示しています
あとは cargo run を実行して 127.0.0.1:8080 にアクセスすれば Hello world! と表示されます

はいこれでおしまいです
簡単ですね
ここから機能を作成したりして Rust との親睦を深めていきたいと思います

https://actix.rs/docs/getting-started が分かりやすかったので機能開発等もこちらのドキュメントを参考に進めていきたいと思っています

参考にした記事

https://actix.rs/docs/getting-started
https://qiita.com/yoshii0110/items/6d70323f01fefcf09682

7
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
0