|
| 1 | +use std::{collections::HashMap, error::Error}; |
| 2 | + |
| 3 | +use config::{builder::AsyncState, AsyncSource, ConfigBuilder, ConfigError, FileFormat}; |
| 4 | + |
| 5 | +use async_trait::async_trait; |
| 6 | +use futures::{select, FutureExt}; |
| 7 | +use warp::Filter; |
| 8 | + |
| 9 | +// Example below presents sample configuration server and client. |
| 10 | +// |
| 11 | +// Server serves simple configuration on HTTP endpoint. |
| 12 | +// Client consumes it using custom HTTP AsyncSource built on top of reqwest. |
| 13 | + |
| 14 | +#[tokio::main] |
| 15 | +async fn main() -> Result<(), Box<dyn Error>> { |
| 16 | + select! { |
| 17 | + r = run_server().fuse() => r, |
| 18 | + r = run_client().fuse() => r |
| 19 | + } |
| 20 | +} |
| 21 | + |
| 22 | +async fn run_server() -> Result<(), Box<dyn Error>> { |
| 23 | + let service = warp::path("configuration").map(|| r#"{ "value" : 123 }"#); |
| 24 | + |
| 25 | + println!("Running server on localhost:5001"); |
| 26 | + |
| 27 | + warp::serve(service).bind(([127, 0, 0, 1], 5001)).await; |
| 28 | + |
| 29 | + Ok(()) |
| 30 | +} |
| 31 | + |
| 32 | +async fn run_client() -> Result<(), Box<dyn Error>> { |
| 33 | + // Good enough for an example to allow server to start |
| 34 | + tokio::time::sleep(tokio::time::Duration::from_secs(3)).await; |
| 35 | + |
| 36 | + let config = ConfigBuilder::<AsyncState>::default() |
| 37 | + .add_async_source(HttpSource { |
| 38 | + uri: "http://localhost:5001/configuration".into(), |
| 39 | + format: FileFormat::Json, |
| 40 | + }) |
| 41 | + .build() |
| 42 | + .await?; |
| 43 | + |
| 44 | + println!("Config value is {}", config.get::<String>("value")?); |
| 45 | + |
| 46 | + Ok(()) |
| 47 | +} |
| 48 | + |
| 49 | +// Actual implementation of AsyncSource can be found below |
| 50 | + |
| 51 | +#[derive(Debug)] |
| 52 | +struct HttpSource { |
| 53 | + uri: String, |
| 54 | + format: FileFormat, |
| 55 | +} |
| 56 | + |
| 57 | +#[async_trait] |
| 58 | +impl AsyncSource for HttpSource { |
| 59 | + async fn collect(&self) -> Result<HashMap<String, config::Value>, ConfigError> { |
| 60 | + reqwest::get(&self.uri) |
| 61 | + .await |
| 62 | + .map_err(|e| ConfigError::Foreign(Box::new(e)))? // error conversion is possible from custom AsyncSource impls |
| 63 | + .text() |
| 64 | + .await |
| 65 | + .map_err(|e| ConfigError::Foreign(Box::new(e))) |
| 66 | + .and_then(|text| { |
| 67 | + self.format |
| 68 | + .parse(Some(&self.uri), &text) |
| 69 | + .map_err(|e| ConfigError::Foreign(e)) |
| 70 | + }) |
| 71 | + } |
| 72 | +} |
0 commit comments