59 lines
1.5 KiB
Rust
59 lines
1.5 KiB
Rust
use reqwest::Client;
|
|
use serde::Serialize;
|
|
|
|
#[derive(Serialize)]
|
|
struct ConsulRegistration {
|
|
name: String,
|
|
address: String,
|
|
port: u16,
|
|
check: ConsulCheck,
|
|
}
|
|
|
|
#[derive(Serialize)]
|
|
struct ConsulCheck {
|
|
http: String,
|
|
interval: String,
|
|
}
|
|
|
|
pub async fn register_service(
|
|
consul_url: &str,
|
|
service_name: &str,
|
|
service_address: &str,
|
|
service_port: u16,
|
|
health_check_url: &str,
|
|
) -> Result<(), Box<dyn std::error::Error>> {
|
|
let registration = ConsulRegistration {
|
|
name: service_name.to_string(),
|
|
address: service_address.to_string(),
|
|
port: service_port,
|
|
check: ConsulCheck {
|
|
http: health_check_url.to_string(),
|
|
interval: "10s".to_string(), // Health check interval
|
|
},
|
|
};
|
|
|
|
let client = Client::new();
|
|
let consul_register_url = format!("{}/v1/agent/service/register", consul_url);
|
|
|
|
client
|
|
.put(&consul_register_url)
|
|
.json(®istration)
|
|
.send()
|
|
.await?
|
|
.error_for_status()?; // Ensure response is successful
|
|
|
|
Ok(())
|
|
}
|
|
|
|
pub async fn deregister_service(consul_url: &str, service_name: &str) -> Result<(), Box<dyn std::error::Error>> {
|
|
let client = Client::new();
|
|
let consul_deregister_url = format!("{}/v1/agent/service/deregister/{}", consul_url, service_name);
|
|
|
|
client
|
|
.put(&consul_deregister_url)
|
|
.send()
|
|
.await?
|
|
.error_for_status()?; // Ensure response is successful
|
|
|
|
Ok(())
|
|
} |