[A-00235] Rust 1000本ノック (1)
Rustを使って色々アプリケーション作るシリーズです。
RustでWebサーバーを立ててブラウザに表示する単純なアプリを作りたいと思います。
まずプロジェクト作成をします。
cargo new hello_app
hello_app/Cargo.tomlファイルに依存関係を記載します。
[package]
name = "hello_app"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8.1"
tokio = { version = "1.43.0", features = ["full"]}
次にビルドします。
cargo build
エラーが起きなければとりあえずOKです。src配下のmain.rsを編集します。
use axum:: {Router, routing::get, response::Html};
#[tokio::main]
async fn main() {
let app = Router::new().route("/", get(handler));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
}
async fn handler() -> Html<&'static str> {
Html("<h1>Hello, Rust and Axum!</h1>")
}
上記を作成したら下記のコマンドを実行します。
cargo build
cargo run
ブラウザにて下記のキャプチャと同じ画面が表示されればOKです。

・Appendix
参考文献はこちら
https://docs.rs/tokio/latest/tokio
https://docs.rs/axum/latest/axum/index.html
https://higmasan.com/rust/getting-started-with-web-applications-in-rust-2023-axum
https://zenn.dev/codemountains/articles/b3c9c176d821e7
https://doc.rust-jp.rs/book-ja/ch03-05-control-flow.html
https://zenn.dev/keisuke333/articles/58a136bb4076dc
https://qiita.com/anqooqie/items/110957797b3d5280c44f
https://medium.com/@rs4528090/how-to-build-a-rest-api-with-rust-65dfb19d1edd
コメントを残す