Skip to content

Commit c66dd73

Browse files
committed
WIP: add get json response
1 parent 6089e85 commit c66dd73

File tree

4 files changed

+44
-56
lines changed

4 files changed

+44
-56
lines changed

docs/chapter1/section3/1_json-response.md

Lines changed: 5 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -7,34 +7,20 @@ JSON について分からない人は
77
:::
88

99
:::tip
10-
Go の構造体についてわからない人は↓を見ると良いです。
10+
Rust の構造体についてわからない人は↓を見ると良いです。
1111

12-
https://go-tour-jp.appspot.com/moretypes/2
12+
https://doc.rust-jp.rs/book-ja/ch05-01-defining-structs.html
1313
:::
1414

15-
JSON をレスポンスとして返すためには、`c.JSON`メソッドに構造体を渡します
16-
先ほどの章で作成した`main.go`に、以下のようなエンドポイントを追加して、`JSON`レスポンスを返してみましょう。
15+
JSON をレスポンスとして返すためには、`Json` に構造体を渡します
16+
先ほどの章で作成した`main.rs`に、以下のようなエンドポイントを追加して、`JSON`レスポンスを返してみましょう。
1717

18-
<<<@/chapter1/section3/src/2-1_json-server.go
18+
<<<@/chapter1/section3/src/2-1_json-server.rs
1919

2020
書き換えたら、<a href='http://localhost:8080/json' target="_blank" rel="noopener noreferrer">localhost:8080/json</a> にアクセスして確認してみましょう。
2121

2222
![](assets/json_server.png)
2323

24-
タグを追加することで構造体のフィールドに対応する、JSON のキー名を指定できます。
25-
Go の構造体のフィールドはパスカルケースですが、JSON のフィールドは普通キャメルケース / スネークケースであるため、`main.go`の構造体を以下のように書き換えましょう。
26-
27-
```go
28-
type jsonData struct {
29-
// Numner -> number (omitemptyは、ゼロ値の場合はそのフィールドを出力しないという意味)
30-
Number int `json:"number,omitempty"`
31-
String string `json:"string,omitempty"`
32-
Bool bool `json:"bool,omitempty"`
33-
}
34-
```
35-
36-
参考: [encoding/json#Marshal](https://pkg.go.dev/encoding/json#Marshal)
37-
3824
## Postmanでリクエストしてみよう
3925

4026
Postman を起動したら、workspace を作成して移動し、`Ctrl + N`->`HTTP`または`Overview`タブの横にある`+`を押して、リクエスト設定画面を開きます。
10.5 KB
Loading

docs/chapter1/section3/src/2-1_json-server.go

Lines changed: 0 additions & 37 deletions
This file was deleted.
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
use axum::{routing::get, Json, Router};
2+
3+
#[tokio::main]
4+
async fn main() {
5+
// 「/json」というパスのエンドポイントを定義
6+
let app = Router::new()
7+
.route("/json", get(json_handler));
8+
9+
// Webサーバーをポート番号8080にバインドする
10+
let listener = tokio::net::TcpListener::bind("127.0.0.1:8080")
11+
.await
12+
.unwrap();
13+
14+
println!("listening on {}", listener.local_addr().unwrap());
15+
16+
// サーバーを起動する
17+
axum::serve(listener, app).await.unwrap();
18+
}
19+
20+
// JSONで返すための構造体を定義
21+
// 構造体を JSON に変換するためにserde::Serializeを導出する
22+
#[derive(serde::Serialize)]
23+
struct JsonData {
24+
number: i32,
25+
string: String,
26+
bool: bool,
27+
}
28+
29+
async fn json_handler() -> Json<JsonData> {
30+
// レスポンスとして返す値を構造体として定義
31+
let res = JsonData {
32+
number: 10,
33+
string: String::from("hoge"),
34+
bool: false,
35+
};
36+
37+
// 構造体をJSONに変換してクライアントに返す
38+
Json(res)
39+
}

0 commit comments

Comments
 (0)