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

时间:2018-09-21 17:46:46

标签: api rust

我正在为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]

如何以所需的方式格式化输出,即将每个余额放在换行符上?

1 个答案:

答案 0 :(得分:0)

我一直在寻找对.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");
        })
})