【发布时间】:2021-11-10 06:08:13
【问题描述】:
我已经使用 Rocket 创建了一个服务器来访问 ipfs URL 的对等信息
程序如下
#[macro_use] extern crate rocket;
use rocket::local::asynchronous::Client;
use rocket::http::hyper::{Request, Response};
use std::collections::HashMap;
use rocket::futures::TryFutureExt;
use std::fmt::Error;
use serde_json::Value;
#[get("/")]
async fn index(){
// https://github.com/rust-lang/rust/issues/63502
let client = reqwest::Client::new();
let data = r#"
{
"name": "ELKA",
"age": 43,
"phones": [
"+44 1234567",
"+44 2345678"
]
}"#;
let doc: Value = serde_json::from_str(data).unwrap();
let resp = client.post("https://_IPFS_URL:5001/api/v0/swarm/peers").send().await.unwrap();
// How to get the JSON response?
if resp.status().is_success() {
println!("success!");
println!("RESP: {:?}", resp);
} else if resp.status().is_server_error() {
println!("server error!");
println!("Something else happened. \n Resp {:?} \n Status: {:?}", resp, resp.status());
} else {
println!("Something else happened. \n Resp {:?} \n Status: {:?}", resp, resp.status());
}
}
#[launch]
fn rocket() -> _ {
rocket::build().mount("/", routes![index])
}
来自的回应
curl -X POST https://_IPFS_URL:5001/api/v0/swarm/peers是
{
"Peers":[
{
"Addr":"/ip4/172.31.20.195/tcp/4001",
"Peer":"183293203CY",
"Latency":"",
"Muxer":"",
"Direction":0,
"Streams":null
}
]
}
我不清楚如何使用 rust 将响应读取为 JSON
我正在使用reqwest 库
如果有人可以提供指导,将不胜感激。
【问题讨论】:
-
@Jmb 你可以添加你的答案,这样我就可以试试了
-
注意,不需要通过解析字符串表示来构造
doc;serde_json::json!-宏可以construct the value directly。 -
reqwest 存储库包含许多示例,包括json_dynamic。您是否尝试过这样做?请注意,您需要使用
jsonfeature 编译 reqwest。 -
@eggyal 他们有 Tokio 的示例,但 Rocket 没有,示例与 Rocket 框架不兼容
标签: rust rust-rocket