conreg_client/network/
mod.rs1use crate::conf::ServerAddr;
2use crate::protocol::response::Res;
3use anyhow::bail;
4use reqwest::StatusCode;
5use reqwest::header::{HeaderMap, HeaderName, HeaderValue};
6use serde::Serialize;
7use serde::de::DeserializeOwned;
8use std::fmt::Debug;
9use std::str::FromStr;
10use std::sync::LazyLock;
11use std::time::Duration;
12
13pub struct Network {
14 client: reqwest::Client,
15}
16
17pub static HTTP: LazyLock<Network> = LazyLock::new(|| {
18 let client = reqwest::ClientBuilder::default()
19 .connect_timeout(Duration::from_secs(1))
20 .read_timeout(Duration::from_secs(60))
21 .build()
22 .unwrap();
23 Network { client }
24});
25
26impl Network {
27 pub async fn get<T: DeserializeOwned + Debug + Default>(
28 &self,
29 url: &str,
30 query: impl Serialize + Debug,
31 headers: Option<Vec<(&str, &str)>>,
32 ) -> anyhow::Result<T> {
33 log::debug!("GET {}, query: {:?}", url, query);
34 let response = self
35 .client
36 .get(url)
37 .query(&query)
38 .headers(match headers {
39 Some(headers) => headers
40 .into_iter()
41 .map(|(k, v)| {
42 (
43 HeaderName::from_str(k).unwrap(),
45 HeaderValue::from_str(v).unwrap_or(HeaderValue::from_str("").unwrap()),
46 )
47 })
48 .collect::<HeaderMap<_>>(),
49 None => HeaderMap::new(),
50 })
51 .send()
52 .await?;
53 if response.status() != StatusCode::OK {
54 bail!("{}", response.text().await?);
55 }
56 let result = response.json::<Res<T>>().await?;
57 if result.code != 0 {
58 bail!("{}", result.msg);
59 }
60 Ok(result.data.unwrap_or(Default::default()))
61 }
62
63 pub async fn post<T: DeserializeOwned + Debug + Default>(
64 &self,
65 url: &str,
66 body: impl Serialize + Debug,
67 ) -> anyhow::Result<T> {
68 log::debug!("POST {}, body: {:?}", url, body);
69 let response = self.client.post(url).json(&body).send().await?;
70 if response.status() != StatusCode::OK {
71 bail!("{}", response.text().await?);
72 }
73 let result = response.json::<Res<T>>().await?;
74 if result.code != 0 {
75 bail!("{}", result.msg);
76 }
77 Ok(result.data.unwrap_or(Default::default()))
78 }
79}
80
81impl ServerAddr {
82 pub fn build_url(&self, path: &str) -> anyhow::Result<String> {
83 match self {
84 ServerAddr::Single(address) => {
85 let url = format!("http://{}{}", address, path);
86 Ok(url)
87 }
88 ServerAddr::Cluster(addresses) => {
89 let address = addresses[fastrand::usize(0..addresses.len())].clone();
90 let url = format!("http://{}{}", address, path);
91 Ok(url)
92 }
93 ServerAddr::Unset => {
94 bail!("discovery server address not set");
95 }
96 }
97 }
98}