0

我是 Rust 的新手,想用一些简单的东西来测试它。该代码基本上是查询外部 API 并返回响应。在这种情况下,响应是一个对象数组。

#![feature(proc_macro_hygiene, decl_macro)]

#[macro_use] extern crate rocket;
extern crate serde;
extern crate serde_json;

#[derive(Deserialize, Debug)]
struct InboundAddress {
    chain: String,
    pub_key: String,
    address: String,
    halted: bool,
    gas_rate: String,
}

#[get("/addresses")]
fn addresses() -> Result<Vec<InboundAddress>, reqwest::Error> {
    let url = "https://midgard.thorchain.info/v2/thorchain/inbound_addresses";
    let addresses: Vec<InboundAddress> = reqwest::blocking::get(url)?.json()?;
    println!("First address chain is: {}", addresses[0].chain);
    Ok(addresses)
}


fn main() {
    rocket::ignite().mount("/", routes![addresses]).launch();
}

错误来自我试图返回的内容Result<Vec<InboundAddress>, reqwest::Error>,说“该特征rocket::response::Responder<'_>未实现std::result::Result<std::vec::Vec<InboundAddress>, reqwest::Error>

json 解析正确,从某些地址注销详细信息有效。如何返回从 Rocket 中的外部 API 查询的对象数组?

4

1 回答 1

0

关键是将 Vec 包装在 Json 中。

#[get("/addresses")]
fn addresses() -> Result<Json<Vec<InboundAddress>>, reqwest::Error> {
    let url = "https://testnet.midgard.thorchain.info/v2/thorchain/inbound_addresses";
    let addresses: Vec<InboundAddress> = reqwest::blocking::get(url)?.json()?;
    Ok(Json(addresses))
}
于 2021-06-07T15:02:46.923 回答