#http-client #blocking #dotenv #requiring #deserialize #ddf #diamond-ddf

ddf-blocking-http-client

为需要阻塞式HTTP客户端的DiamondDDF项目提供的便利crate

3个版本

0.0.3 2022年8月29日
0.0.2 2022年8月26日
0.0.1 2022年8月26日

#37 in #dotenv

MIT/Apache

12KB
119

这是一个用于处理HTTP请求和错误的便利crate。

示例

use ddf_blocking_http_client::Client;
use ddf_blocking_http_client::HttpResult;
use serde::Deserialize;

use dotenv::dotenv;
use std::env;

// dotenv is being used for lack of an example not requiring private keys and public wallet addresses.
// dotenv is not required for this crate to work.
dotenv::dotenv().ok();
let api_key = env::var("API_KEY").unwrap();
let wallet_address = env::var("PUBLIC_WALLET_ADDRESS").unwrap();

#[derive(Debug, Deserialize)]
struct Balance {
    result: String
}

let client = Client::new();

let url = 
    &[
        "https://api.etherscan.io/api",
        "?module=account",
        "&action=balance",
        "&address=", &wallet_address,
        "&tag=latest",
        "&apikey=", &api_key
    ].concat();

// Here is the main feature, Balance is the data structure expected back, defined above.
// You define your own struct and use the serde crate and tag the struct with #[derive(Deserialize)]
// and put the name of your struct where our example is using "Balance".
// the 10 means we are going to try 10 times, if there is a too_many_requests response, or 
// an unknown error (perhaps our crate just doesn't handle it yet) then it will wait 1 second and try again.
// each time it will double the wait time. The return type is HttpResult<T>

let balance = client.get::<Balance>(url, 10).unwrap().result;

dbg!(&balance);

// If you are unsure the shape of the data, you can at first use the "get_as_text" function.
// Here is an example of that "get_as_text" function, so you can get a look at all the fields to base your struct off of:

let balance = client.get_as_text(&url);

dbg!(&balance);

依赖

~4–18MB
~245K SLoC