longport_httpcli/
config.rs

1use crate::HttpClientError;
2
3/// Configuration options for Http client
4#[derive(Debug, Clone)]
5pub struct HttpClientConfig {
6    /// HTTP API url
7    pub(crate) http_url: Option<String>,
8    /// App key
9    pub(crate) app_key: String,
10    /// App secret
11    pub(crate) app_secret: String,
12    /// Access token
13    pub(crate) access_token: String,
14}
15
16impl HttpClientConfig {
17    /// Create a new `HttpClientConfig`
18    pub fn new(
19        app_key: impl Into<String>,
20        app_secret: impl Into<String>,
21        access_token: impl Into<String>,
22    ) -> Self {
23        Self {
24            http_url: None,
25            app_key: app_key.into(),
26            app_secret: app_secret.into(),
27            access_token: access_token.into(),
28        }
29    }
30
31    /// Create a new `HttpClientConfig` from the given environment variables
32    ///
33    /// # Variables
34    ///
35    /// - LONGPORT_APP_KEY
36    /// - LONGPORT_APP_SECRET
37    /// - LONGPORT_ACCESS_TOKEN
38    /// - LONGPORT_HTTP_URL
39    pub fn from_env() -> Result<Self, HttpClientError> {
40        let _ = dotenv::dotenv();
41
42        let app_key =
43            std::env::var("LONGPORT_APP_KEY").map_err(|_| HttpClientError::MissingEnvVar {
44                name: "LONGPORT_APP_KEY",
45            })?;
46        let app_secret =
47            std::env::var("LONGPORT_APP_SECRET").map_err(|_| HttpClientError::MissingEnvVar {
48                name: "LONGPORT_APP_SECRET",
49            })?;
50        let access_token =
51            std::env::var("LONGPORT_ACCESS_TOKEN").map_err(|_| HttpClientError::MissingEnvVar {
52                name: "LONGPORT_ACCESS_TOKEN",
53            })?;
54
55        let mut config = Self::new(app_key, app_secret, access_token);
56        config.http_url = std::env::var("LONGPORT_HTTP_URL").ok();
57        Ok(config)
58    }
59
60    /// Specifies the url of the OpenAPI server.
61    ///
62    /// Default: <https://openapi.longportapp.com>
63    /// NOTE: Usually you don't need to change it.
64    #[must_use]
65    pub fn http_url(self, url: impl Into<String>) -> Self {
66        Self {
67            http_url: Some(url.into()),
68            ..self
69        }
70    }
71}