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



我正在为 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类型变量。

在这个箱子的二进制文件中,我已经读取了一个包含以行分隔的以太坊地址列表的文件,并正在每个地址上调用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");
})
})

最新更新