diff --git a/docs/chapter2/section4/1_image.md b/docs/chapter2/section4/1_image.md index e1bc9531..17e2c4a9 100644 --- a/docs/chapter2/section4/1_image.md +++ b/docs/chapter2/section4/1_image.md @@ -4,36 +4,30 @@ ### コードを書く -`naro_server`というディレクトリを作り、その中でコードを書いてください。第 1 部でやったように、 Go を使って下の条件を満たすサーバーアプリケーションを作ってください。 +`naro_server`というディレクトリを作り、その中でコードを書いてください。第 1 部でやったように、 Rust を使って下の条件を満たすサーバーアプリケーションを作ってください。 - `/greeting`への GET リクエストに、環境変数 `GREETING_MESSAGE`の値を返す。 - 起動するポートを環境変数`PORT`で指定できる。 -`go mod`コマンドで外部ライブラリを管理しましょう。 - -https://go.dev/ref/mod - -```sh -go mod init naro_server -go mod tidy -``` - :::details 答え -<<< @/chapter2/section4/src/main.go +<<< @/chapter2/section4/src/main.rs + +※ `axum` や `tokio` の依存関係を追加する必要があります。 ::: ### ビルドして実行する -今までは`go run`コマンドでプログラムを実行していましたが、Go では`go build`コマンドでコンパイルして実行ファイルを生成し、そのファイルを用いてプログラムを実行できます。 +今までは`cargo run`コマンドでプログラムを実行していましたが、Rust では`cargo build`コマンドでコンパイルして実行ファイルを生成し、そのファイルを用いてプログラムを実行できます。 ```sh -go build -o server +cargo build --release ``` -上のコマンドを実行すると`server`というファイルが生成され、`./server`で実行できます。 +`--release`オプションをつけることで、最適化されたバイナリが生成されます。 +以下のコマンドで実行できます。 ```sh -GREETING_MESSAGE="こんにちは" PORT="8080" ./server +GREETING_MESSAGE="こんにちは" PORT="8080" ./target/release/naro-server ``` 実行前に環境変数を設定しています。 diff --git a/docs/chapter2/section4/src/main.go b/docs/chapter2/section4/src/main.go deleted file mode 100644 index 673ab259..00000000 --- a/docs/chapter2/section4/src/main.go +++ /dev/null @@ -1,31 +0,0 @@ -package main - -import ( - "log" - "net/http" - "os" - - "github.com/labstack/echo/v4" -) - -func main() { - port, ok := os.LookupEnv("PORT") - if !ok { - log.Fatal("failed to get env PORT") - } - - e := echo.New() - - e.GET("/greeting", greetingHandler) - - e.Logger.Fatal(e.Start(":" + port)) -} - -func greetingHandler(c echo.Context) error { - greeting, ok := os.LookupEnv("GREETING_MESSAGE") - if !ok { - return echo.NewHTTPError(http.StatusInternalServerError, "failed to get env GREETING_MESSAGE") - } - - return c.String(http.StatusOK, greeting) -} diff --git a/docs/chapter2/section4/src/main.rs b/docs/chapter2/section4/src/main.rs new file mode 100644 index 00000000..70341915 --- /dev/null +++ b/docs/chapter2/section4/src/main.rs @@ -0,0 +1,25 @@ +use axum::{http::StatusCode, routing::get, Router}; + +#[tokio::main] +async fn main() { + let port = std::env::var("PORT") + .expect("failed to get env PORT") + .parse::() + .expect("failed to parse PORT"); + + let app = Router::new().route("/greeting", get(greeting_handler)); + + let addr = std::net::SocketAddr::from(([127, 0, 0, 1], port)); + + let listener = tokio::net::TcpListener::bind(&addr).await.unwrap(); + + println!("Listening on {}", addr); + + axum::serve(listener, app).await.unwrap(); +} + +async fn greeting_handler() -> Result<(StatusCode, String), StatusCode> { + let greeting = + std::env::var("GREETING_MESSAGE").map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?; + Ok((StatusCode::OK, greeting)) +}