From d583c17782977c3547da563a62e6f9f4fada15f3 Mon Sep 17 00:00:00 2001 From: Quentin Dufour Date: Fri, 22 May 2020 10:33:09 +0200 Subject: We are now able to watch --- src/consul.rs | 24 ++++++++++++++++++------ src/main.rs | 6 ++++-- 2 files changed, 22 insertions(+), 8 deletions(-) diff --git a/src/consul.rs b/src/consul.rs index e438605..b06f62d 100644 --- a/src/consul.rs +++ b/src/consul.rs @@ -1,6 +1,6 @@ use serde::{Serialize, Deserialize}; use std::collections::HashMap; -use anyhow::Result; +use anyhow::{Result, anyhow}; #[derive(Serialize, Deserialize, Debug)] pub struct ServiceEntry { @@ -14,20 +14,32 @@ pub struct CatalogNode { pub struct Consul { client: reqwest::Client, - url: String + url: String, + idx: Option } impl Consul { pub fn new(url: &str) -> Self { return Self { client: reqwest::Client::new(), - url: url.to_string() + url: url.to_string(), + idx: None }; } - pub async fn catalog_node(&self, host: &str) -> Result { - let url = format!("{}/v1/catalog/node/{}", self.url, host); - let resp: CatalogNode = self.client.get(&url).send().await?.json().await?; + pub async fn watch_node(&mut self, host: &str) -> Result { + 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::()?), + None => return Err(anyhow!("X-Consul-Index header not found")) + }; + + let resp: CatalogNode = http.json().await?; return Ok(resp) } } diff --git a/src/main.rs b/src/main.rs index ead8c32..028f16e 100644 --- a/src/main.rs +++ b/src/main.rs @@ -14,9 +14,11 @@ async fn main() { let diplo = Diplonat::new().await.expect("Setup failed"); diplo.listen().await.expect("A runtime error occured"); */ - let c = Consul::new("http://127.0.0.1:8500"); - let cn = c.catalog_node("lheureduthe").await.expect("Failed to fetch API"); + let mut c = Consul::new("http://127.0.0.1:8500"); + let cn = c.watch_node("lheureduthe").await.expect("Failed to fetch API"); println!("{:#?}", cn); + let cn2 = c.watch_node("lheureduthe").await.expect("Failed to fetch API"); + println!("{:#?}", cn2); /* let gateway = match search_gateway(Default::default()).await { -- cgit v1.2.3