config_plus_core/http/
mod.rs

1use config::{ConfigError, FileFormat, Format, Map, Source, Value};
2use std::fmt::Debug;
3pub type HeaderMap = reqwest::header::HeaderMap;
4
5/// 请求方法,只支持[GET,POST]两种
6#[derive(Debug, Clone)]
7pub enum HttpMethod {
8    Get,
9    Post,
10}
11impl Default for HttpMethod {
12    fn default() -> Self {
13        HttpMethod::Get
14    }
15}
16
17/// http源
18#[derive(Debug, Clone)]
19pub struct Http {
20    url: String,
21    method: HttpMethod,
22    format: FileFormat,
23}
24
25impl Http {
26
27    pub fn new<S: AsRef<str>>(url: S, format: FileFormat, method: HttpMethod) -> Self {
28        Http {
29            url: url.as_ref().to_string(),
30            format,
31            method,
32        }
33    }
34    pub fn with(url: &str, format: &str, method: &str) -> Self {
35        Http {
36            url:  url.to_string(),
37            format: Http::convert_format(format),
38            method: Http::convert_method(method),
39        }
40    }
41    
42    fn convert_format(format: &str) -> FileFormat{
43        match format { 
44            #[cfg(feature = "toml")]
45            "toml" => FileFormat::Toml,
46            #[cfg(feature = "json")]
47            "json" => FileFormat::Json,
48            #[cfg(feature = "yaml")]
49            "yaml" => FileFormat::Yaml,
50            #[cfg(feature = "ini")]
51            "ini" => FileFormat::Ini,
52            #[cfg(feature = "ron")]
53            "ron" => FileFormat::Ron,
54            #[cfg(feature = "json5")]
55            "json5" => FileFormat::Json5,
56            _ => unreachable!("不支持格式"),
57        }
58    }
59
60    fn convert_method(method: &str) -> HttpMethod{
61        match method {
62            "get" => HttpMethod::Get,
63            "post" => HttpMethod::Post,
64            _ => unreachable!("没有启用特性"),
65        }
66    }
67}
68
69impl Source for Http {
70    fn clone_into_box(&self) -> Box<dyn Source + Send + Sync> {
71        Box::new((*self).clone())
72    }
73
74    fn collect(&self) -> Result<Map<String, Value>, ConfigError> {
75        let client = match reqwest::blocking::Client::builder().build() {
76            Ok(client) => client,
77            Err(e) => return Err(ConfigError::Message(e.to_string())),
78        };
79
80        let response = match self.method {
81            HttpMethod::Get => client.get(&self.url).send(),
82            HttpMethod::Post => client.post(&self.url).send(),
83        };
84
85        let response = match response {
86            Ok(response) => response,
87            Err(e) => return Err(ConfigError::Message(e.to_string())),
88        };
89
90        let content = match response.text() {
91            Ok(content) => content,
92            Err(e) => return Err(ConfigError::Message(e.to_string())),
93        };
94
95        let format = self.format;
96
97        format
98            .parse(None, &content)
99            .map_err(|cause| ConfigError::Message(cause.to_string()))
100    }
101}