config_plus/http/
mod.rs

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