|
|||||
Actix webでJSONをPOSTするActix webでJSONをPOSTする。 まずはパッケージを作成する。 $ cargo new hello-actix-web-json Cargo.tomlに依存関係を追加する。
[dependencies]
actix-web = "3"
serde = { version = "1.0", features = ["derive"] }
次に、src/main.rsに以下のコードを書く。useでDeserializeの使用を宣言する。JSONでPOSTしたいオブジェクトに#[derive(Deserialize)]を付加する。JSONでPOSTしたデータはそのオブジェクトに変換(Deserialize)され、引数として渡される。 以下では、取得したJSONのデータを文字列として返す。
use actix_web::{post, web, App, HttpServer};
use serde::Deserialize;
#[derive(Deserialize)]
struct Info {
str: String,
num: isize,
arr: Vec::<isize>,
}
#[post("/postjson")]
async fn index(info: web::Json<Info>) -> String {
format!("str: {} num {} arr: {:?}", info.str, info.num, info.arr)
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| App::new().service(index))
// localhostからのみアクセスするなら127.0.0.1
//.bind("127.0.0.1:8080")?
// EC2等に配置して外部からアクセスするなら0.0.0.0
.bind("0.0.0.0:8080")?
.run()
.await
}
これをcargo runコマンドで実行すると、Webサーバが8080ポートで起動する。
$ cargo run
Finished dev [unoptimized + debuginfo] target(s) in 0.60s
Running `target/debug/hello-actix-web-json`
例えば、起動したサーバにcurlでJSONをPOSTする。POSTしたデータがオブジェクトに変換され、結果的に文字列として返されるのが確認できる。
$ curl -X POST -H 'Content-Type: application/json' -d '{ "str": "テスト1", "num": 100, "arr": [1, 2, 3] }' http://localhost:8080/postjson
str: テスト1 num 100 arr: [1, 2, 3]
(2021/01/20)
Copyright© 2004-2021 モバイル開発系(K) All rights reserved.
[Home]
|
|||||