tin-nacos-wrapper 0.1.0

A Rust library for Nacos service discovery and configuration management
Documentation
use crate::client::NacosClient;
use crate::error::{Error, Result};
use crate::http::HttpClient;
use serde::de::DeserializeOwned;
use std::collections::HashMap;

/// 远程服务调用工具类
pub struct RemoteServiceClient;

impl RemoteServiceClient {
    /// 获取服务地址
    pub async fn get_service_address(
        nacos_client: &NacosClient,
        service_name: &str,
    ) -> Result<String> {
        let client = nacos_client
            .get_naming_service()
            .select_one_healthy_instance(service_name.into(), None, vec![], false)
            .await
            .map_err(Error::Nacos)?;

        Ok(client.ip_and_port())
    }

    /// 发送POST请求并处理响应
    pub async fn post_with_response<T>(
        url: &str,
        json_body: &serde_json::Value,
        headers: Option<HashMap<String, String>>,
    ) -> Result<T>
    where
        T: DeserializeOwned,
    {
        let response = HttpClient::new()
            .post(url, json_body, headers)
            .await
            .map_err(Error::Request)?;

        let status = response.status();
        if !status.is_success() {
            return Err(Error::Service(format!(
                "Request failed with status: {status}"
            )));
        }

        let text = response.text().await.map_err(|e| {
            log::error!("读取响应文本失败: {e}");
            Error::Request(e)
        })?;
        log::debug!("响应文本: {text}");

        let api_resp = serde_json::from_str::<T>(&text).map_err(|e| {
            log::error!("反序列化失败: {e}");
            Error::Json(e)
        })?;

        Ok(api_resp)
    }

    /// 发送GET请求并处理响应
    pub async fn get_with_response<T>(
        url: &str,
        headers: Option<HashMap<String, String>>,
    ) -> Result<T>
    where
        T: DeserializeOwned,
    {
        log::debug!("发送GET请求到: {url},headers: {headers:?}");

        let response = HttpClient::new()
            .get(url, headers)
            .await
            .map_err(Error::Request)?;

        let status = response.status();
        if !status.is_success() {
            return Err(Error::Service(format!(
                "Request failed with status: {status}"
            )));
        }

        let text = response.text().await.map_err(|e| {
            log::error!("读取响应文本失败: {e}");
            Error::Request(e)
        })?;
        log::debug!("响应文本: {text}");

        let api_resp = serde_json::from_str::<T>(&text).map_err(|e| {
            log::error!("反序列化失败: {e}");
            Error::Json(e)
        })?;

        Ok(api_resp)
    }
}