gpt4 book ai didi

api - 如何在返回 JSON 的 API 的多个调用之间添加换行符?

转载 作者:行者123 更新时间:2023-11-29 08:32:23 25 4
gpt4 key购买 nike

我正在为 Etherscan.io 开发 API 包装器。我有 get_balance() 处理几个问题:

use super::Config;
use hyper::rt::{Future, Stream};
use hyper::{Body, Client};
use hyper_tls::HttpsConnector;
use serde_json::from_slice;
use std::io::{self, Write};

#[derive(Deserialize)]
struct Account<'a> {
result: &'a [u8],
}

pub fn get_balance(config: Config) -> impl Future<Item = (), Error = ()> {
let uri = format!(
"https://api.etherscan.io/api?module={}&action={}&address={}&tag={}&apiKey={}",
config.module, config.action, config.address, config.tag, config.api_key
).parse()
.unwrap();

let https = HttpsConnector::new(4).unwrap();
let client = Client::builder().build::<_, Body>(https);

client
.get(uri)
.and_then(|res| {
res.into_body().for_each(|chunk| {
let data: Account = from_slice(&chunk).unwrap();
io::stdout()
.write_all(data.result)
.map_err(|e| panic!("Something went wrong!, {}", e))
})
}).map_err(|e| {
eprintln!("Error {}", e);
})
}

现在,我正在使用 serde_json 将 Etherscan API 的 JSON 输出中的 result 字段反序列化为 Account 类型变量。

在这个 crate 的二进制文件中,我读入了一个包含以行分隔的以太坊地址列表的文件,并在每个地址上调用 get_balance 函数。目前,输出看起来像这样

Grabbing balances..
2978949000000000000050000000000118989773837777777707832422000000000077725000000000005585715000000000632954201591000000000000039261000000000922242282421612059956805551700000009340396200000000001302155554000000000001024761480000000000000646546600000000025849226140000000173919401191242898017721300000000000282583067321734110921765800000000010664815135755183661247667868029222166231631200777777777719780855300000000020000000000009862760431183982253209705167363654310198841461200000000000422146084184411875600927519797468763322494071578107259000000000000460845548541297500001497258879653777777777097542367974112844500097065356751518011568537848158458245828091288718199214820000000000012229358000000000019172756010000000000818949139302890483000000000000671348000000000000396900000000000000004692796996935622836101639000000000004313773803864317079183499000000000001851446000000292904912031700000000002833822400000000118576145806291502820102991980000000000031095375771474016024005236052920127528866968915028175902833735562412900300

如您所见,每个余额都一个接一个地打印出来,没有换行符来分隔它们。此外,输出相当延迟,就好像它在写入屏幕之前等待缓冲区被填满。这是因为用于调用 write_all 的类型是 &[u8] 吗?

如何以我正在寻找的方式格式化输出,即每个余额换行?

最佳答案

调用 .map() 是我一直在寻找的:

client.get(uri).and_then(|res| {
res.into_body()
.for_each(|chunk| {
let data: Account = from_slice(&chunk).unwrap();
io::stdout()
.write_all(data.result)
.map_err(|e| panic!("Something went wrong!, {}", e))
}).map(|_| {
print!("\n");
})
})

关于api - 如何在返回 JSON 的 API 的多个调用之间添加换行符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52448756/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com