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