- update: service discovery now supports retrieving multiple service nodes
This commit is contained in:
@@ -1,48 +1,40 @@
|
||||
use serde::Deserialize;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Address {
|
||||
Address: String,
|
||||
Port: u16,
|
||||
#[derive(Debug, Deserialize)]
|
||||
struct ServiceNode {
|
||||
ServiceAddress: String,
|
||||
ServicePort: u16,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct TaggedAddresses {
|
||||
lan_ipv4: Address,
|
||||
wan_ipv4: Address,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Weights {
|
||||
Passing: u8,
|
||||
Warning: u8,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
pub struct Service {
|
||||
pub ID: String,
|
||||
pub Service: String,
|
||||
pub Tags: Vec<String>,
|
||||
pub Port: u16,
|
||||
pub Address: String,
|
||||
pub TaggedAddresses: TaggedAddresses,
|
||||
pub Weights: Weights,
|
||||
pub EnableTagOverride: bool,
|
||||
pub ContentHash: String,
|
||||
pub Datacenter: String,
|
||||
}
|
||||
|
||||
pub async fn get_service_address(consul_url: &str, service_name: &str) -> Result<(Service), Box<dyn std::error::Error>> {
|
||||
pub async fn get_service_address(consul_url: &str, service_name: &str) -> Result<Vec<(String, u16)>, Box<dyn std::error::Error>> {
|
||||
let client = reqwest::Client::new();
|
||||
let consul_service_url = format!("{}/v1/agent/service/{}", consul_url, service_name);
|
||||
let consul_service_url = format!("{}/v1/catalog/service/{}", consul_url, service_name);
|
||||
|
||||
let response = client
|
||||
.get(&consul_service_url)
|
||||
.send()
|
||||
.await?
|
||||
.error_for_status()?
|
||||
.json::<Service>()
|
||||
.await?; // Ensure response is successful
|
||||
.await?;
|
||||
|
||||
Ok(response)
|
||||
if !response.status().is_success() {
|
||||
return Err(format!(
|
||||
"Failed to fetch service nodes for '{}': {}",
|
||||
service_name, response.status()
|
||||
)
|
||||
.into());
|
||||
}
|
||||
|
||||
// Deserialize the response into a Vec<ServiceNode>
|
||||
let nodes: Vec<ServiceNode> = response.json().await?;
|
||||
|
||||
// Map the nodes to (address, port) tuples
|
||||
let addresses: Vec<(String, u16)> = nodes
|
||||
.into_iter()
|
||||
.map(|node| (node.ServiceAddress, node.ServicePort))
|
||||
.collect();
|
||||
|
||||
if addresses.is_empty() {
|
||||
Err(format!("No nodes found for service '{}'", service_name).into())
|
||||
} else {
|
||||
Ok(addresses)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user