diplonat/src/consul.rs

46 lines
1.1 KiB
Rust
Raw Normal View History

2020-05-21 21:04:21 +00:00
use serde::{Serialize, Deserialize};
use std::collections::HashMap;
2020-05-22 08:33:09 +00:00
use anyhow::{Result, anyhow};
2020-05-21 21:04:21 +00:00
#[derive(Serialize, Deserialize, Debug)]
pub struct ServiceEntry {
2020-05-22 12:17:48 +00:00
pub Tags: Vec<String>
2020-05-21 21:04:21 +00:00
}
#[derive(Serialize, Deserialize, Debug)]
pub struct CatalogNode {
2020-05-22 12:17:48 +00:00
pub Services: HashMap<String, ServiceEntry>
2020-05-21 21:04:21 +00:00
}
pub struct Consul {
client: reqwest::Client,
2020-05-22 08:33:09 +00:00
url: String,
idx: Option<u64>
2020-05-21 21:04:21 +00:00
}
impl Consul {
pub fn new(url: &str) -> Self {
return Self {
client: reqwest::Client::new(),
2020-05-22 08:33:09 +00:00
url: url.to_string(),
idx: None
2020-05-21 21:04:21 +00:00
};
}
2020-05-22 08:33:09 +00:00
pub async fn watch_node(&mut self, host: &str) -> Result<CatalogNode> {
let url = match self.idx {
Some(i) => format!("{}/v1/catalog/node/{}?index={}", self.url, host, i),
None => format!("{}/v1/catalog/node/{}", self.url, host)
};
let http = self.client.get(&url).send().await?;
self.idx = match http.headers().get("X-Consul-Index") {
Some(v) => Some(v.to_str()?.parse::<u64>()?),
None => return Err(anyhow!("X-Consul-Index header not found"))
};
let resp: CatalogNode = http.json().await?;
2020-05-21 21:04:21 +00:00
return Ok(resp)
}
}