|
|||||
Actix webでJSONを返すActix webでJSONレスポンスを返す。 まずはパッケージを作成する。 $ cargo new hello-actix-web-json Cargo.tomlに依存関係を追加する。 [dependencies] actix-web = "3" Raw文字列リテラルを使ってJSONレスポンスを返す次に、src/main.rsに以下のコードを書く。JSONとして返却する文字列は、Raw文字列リテラルを利用するとエスケープせずにそのまま書けるので便利だ。返却時のcontent-typeとして、content_type()で"application/json"を指定する。
use actix_web::{get, App, HttpResponse, HttpServer};
#[get("/getjson")]
async fn index() -> HttpResponse {
HttpResponse::Ok()
.content_type("application/json")
.body(r#"{"str":"テスト1","num":100,"arr":[1,2,3]}"#)
}
#[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でアクセスすれば結果が得られる。content-typeも"application/json"となっているのが確認できる。
$ curl -i http://localhost:8080/getjson
HTTP/1.1 200 OK
content-length: 46
content-type: application/json
date: Tue, 12 Jan 2021 23:55:01 GMT
{"str":"テスト1","num":100,"arr":[1,2,3]}
Serdeを使ってJSONレスポンスを返すSerdeはRustのデータ型をJSONに変換したり、あるいはその逆を行うことができる。Actix WebでSerdeを使えば、RustのデータをJSONレスポンスとして返すことができる。Serdeを使うにはCargo.tomlに依存関係を追加する。
[dependencies]
actix-web = "3"
serde = { version = "1.0", features = ["derive"] }
RustのオブジェクトをJSONに変換するには、useでSerializeの使用を宣言する。JSONで返却したいオブジェクトに#[derive(Serialize)]を付加する。後は、そのオブジェクトをResponseBuilderのjson()に渡してやればJSONが返却される。
use actix_web::{get, App, HttpResponse, HttpServer};
use serde::Serialize;
#[derive(Serialize)]
struct MyObj {
str: String,
num: isize,
arr: Vec::<isize>,
}
#[get("/getjson")]
async fn index() -> HttpResponse {
HttpResponse::Ok().json(MyObj {
str: "テスト2".to_string(),
num: 100,
arr: vec![1, 2, 3],
})
}
#[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
}
Vecは配列に変換されるようだ。
$ curl -i http://localhost:8080/getjson
HTTP/1.1 200 OK
content-length: 46
content-type: application/json
date: Wed, 13 Jan 2021 00:34:04 GMT
{"str":"テスト2","num":100,"arr":[1,2,3]}
(2021/01/12)
Copyright© 2004-2021 モバイル開発系(K) All rights reserved.
[Home]
|
|||||