File tree Expand file tree Collapse file tree 4 files changed +44
-56
lines changed Expand file tree Collapse file tree 4 files changed +44
-56
lines changed Original file line number Diff line number Diff line change @@ -7,34 +7,20 @@ JSON について分からない人は
7
7
:::
8
8
9
9
::: tip
10
- Go の構造体についてわからない人は↓を見ると良いです。
10
+ Rust の構造体についてわからない人は↓を見ると良いです。
11
11
12
- https://go-tour- jp.appspot.com/moretypes/2
12
+ https://doc.rust- jp.rs/book-ja/ch05-01-defining-structs.html
13
13
:::
14
14
15
- JSON をレスポンスとして返すためには、` c.JSON ` メソッドに構造体を渡します 。
16
- 先ほどの章で作成した` main.go ` に、以下のようなエンドポイントを追加して、` JSON ` レスポンスを返してみましょう。
15
+ JSON をレスポンスとして返すためには、` Json ` に構造体を渡します 。
16
+ 先ほどの章で作成した` main.rs ` に、以下のようなエンドポイントを追加して、` JSON ` レスポンスを返してみましょう。
17
17
18
- <<<@/chapter1/section3/src/2-1_json-server.go
18
+ <<<@/chapter1/section3/src/2-1_json-server.rs
19
19
20
20
書き換えたら、<a href =' http://localhost:8080/json ' target =" _blank " rel =" noopener noreferrer " >localhost:8080/json</a > にアクセスして確認してみましょう。
21
21
22
22
![ ] ( assets/json_server.png )
23
23
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
-
38
24
## Postmanでリクエストしてみよう
39
25
40
26
Postman を起動したら、workspace を作成して移動し、` Ctrl + N ` ->` HTTP ` または` Overview ` タブの横にある` + ` を押して、リクエスト設定画面を開きます。
Load Diff This file was deleted.
Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments