-
Notifications
You must be signed in to change notification settings - Fork 8
/
custom_config.rs
87 lines (75 loc) · 2.3 KB
/
custom_config.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
//! # Custom Configuration File usage.
//!
//! Shows how to:
//! - Define a custom configuration file and use it with the API.
use std::process::exit;
use serde::{Deserialize, Serialize};
use cbadv::config::{self, ApiConfig, ConfigFile};
use cbadv::RestClient;
/// `[general]` section in the configuration file.
#[derive(Serialize, Deserialize, Debug, Clone)]
struct GeneralConfig {
/// Product being obtained for testing purposes.
pub product_id: String,
}
/// Custom configuration with a `[general]` section containing a `product_id`.
#[derive(Serialize, Deserialize, Debug, Clone)]
struct MyConfig {
/// `[general]` section.
pub general: GeneralConfig,
/// `[coinbase]` section of the configuration.
pub coinbase: ApiConfig,
}
impl MyConfig {
/// Creates a new instance of the custom configuration.
pub fn new() -> Self {
let general = GeneralConfig {
product_id: "BTC-USD".to_string(),
};
Self {
general,
coinbase: config::new(),
}
}
}
impl ConfigFile for MyConfig {
fn coinbase(&self) -> &ApiConfig {
&self.coinbase
}
}
#[tokio::main]
async fn main() {
// Load the configuration file.
let config: MyConfig = match config::load("config.toml") {
Ok(c) => c,
Err(err) => {
println!("Could not load configuration file.");
if config::exists("config.toml") {
println!("File exists, {}", err);
exit(1);
}
// Create a new configuration file with defaults.
config::save(&MyConfig::new(), "config.toml").unwrap();
println!("Empty configuration file created, please update it.");
exit(1);
}
};
// Create a client to interact with the API.
let mut client = match RestClient::from_config(&config) {
Ok(c) => c,
Err(why) => {
eprintln!("!ERROR! {}", why);
exit(1)
}
};
// Pull a singular product from the Product API.
println!("Getting product: {}.", config.general.product_id);
let product = match client.product.get(&config.general.product_id).await {
Ok(p) => p,
Err(err) => {
println!("{}", err);
exit(1);
}
};
println!("{:#?}\n\n", product);
}