Skip to main content

x_one/xhttp/
config.rs

1//! xhttp 配置结构体
2//!
3//! 对应 `application.yml` 中的 `XHttp` 节点。
4//!
5//! ```yaml
6//! XHttp:
7//!   Timeout: "30s"
8//!   DialTimeout: "10s"
9//!   PoolMaxIdlePerHost: 10
10//! ```
11
12use serde::Deserialize;
13
14/// XHttp 配置 key
15pub const XHTTP_CONFIG_KEY: &str = "XHttp";
16
17/// XHttp 配置
18///
19/// # 配置示例
20/// ```yaml
21/// XHttp:
22///   Timeout: "30s"
23///   DialTimeout: "10s"
24///   DialKeepAlive: "30s"
25///   PoolMaxIdlePerHost: 10
26/// ```
27#[derive(Debug, Deserialize, Clone)]
28pub struct XHttpConfig {
29    /// 请求超时(duration 字符串,默认 "30s")
30    #[serde(rename = "Timeout", default = "default_timeout")]
31    pub timeout: String,
32
33    /// 连接超时(duration 字符串,默认 "10s")
34    #[serde(rename = "DialTimeout", default = "default_dial_timeout")]
35    pub dial_timeout: String,
36
37    /// Keep-alive 时间(duration 字符串,默认 "30s")
38    #[serde(rename = "DialKeepAlive", default = "default_dial_keep_alive")]
39    pub dial_keep_alive: String,
40
41    /// 连接池每个主机最大空闲数(默认 10)
42    #[serde(rename = "PoolMaxIdlePerHost", default = "default_pool_max_idle")]
43    pub pool_max_idle_per_host: usize,
44}
45
46fn default_timeout() -> String {
47    "30s".to_string()
48}
49fn default_dial_timeout() -> String {
50    "10s".to_string()
51}
52fn default_dial_keep_alive() -> String {
53    "30s".to_string()
54}
55fn default_pool_max_idle() -> usize {
56    10
57}
58
59/// 加载 XHttp 配置
60pub(crate) fn load_config() -> XHttpConfig {
61    crate::xconfig::parse_config::<XHttpConfig>(XHTTP_CONFIG_KEY).unwrap_or_default()
62}
63
64impl Default for XHttpConfig {
65    fn default() -> Self {
66        Self {
67            timeout: default_timeout(),
68            dial_timeout: default_dial_timeout(),
69            dial_keep_alive: default_dial_keep_alive(),
70            pool_max_idle_per_host: default_pool_max_idle(),
71        }
72    }
73}