chml_api/
lib.rs

1use crate::res::ApiError;
2// utils
3pub mod prelude;
4pub mod res;
5// modules
6pub mod node;
7pub mod panel;
8pub mod tunnel;
9pub mod user;
10pub mod util;
11
12use dotenvy::dotenv;
13use std::env;
14
15/// 如果token能统一位置就好了,可以更抽象和简化,一般都用 Authorization: Bearer <token> 这种形式
16pub struct ChmlApi {
17    pub base_url: String,
18    pub token: Option<String>,
19    pub client: reqwest::Client,
20}
21
22impl ChmlApi {
23    pub fn new(base_url: &str) -> Self {
24        ChmlApi {
25            base_url: base_url.to_string(),
26            token: None,
27            client: reqwest::Client::new(),
28        }
29    }
30
31    pub fn from_env() -> Result<Self, std::env::VarError> {
32        dotenv().ok();
33        let base_url = env::var("CHML_API_BASE_URL")?;
34        let token = env::var("CHML_API_TOKEN")?;
35        Ok(Self {
36            base_url,
37            token: Some(token),
38            client: reqwest::Client::new(),
39        })
40    }
41
42    pub fn new_with_token(base_url: &str, token: &str) -> Self {
43        ChmlApi {
44            base_url: base_url.to_string(),
45            token: Some(token.to_string()),
46            client: reqwest::Client::new(),
47        }
48    }
49
50    pub fn endpoint(&self, path: &str) -> String {
51        format!("{}{}", self.base_url, path)
52    }
53
54    pub fn set_token(&mut self, token: &str) {
55        self.token = Some(token.to_string());
56    }
57
58    pub fn get_token(&self) -> Result<&str, ApiError> {
59        self.token.as_deref().ok_or(ApiError::NoToken)
60    }
61}
62
63pub fn init_logger() {
64    let subscriber = tracing_subscriber::FmtSubscriber::builder()
65        .with_env_filter("debug") // RUST_LOG=debug 可覆盖
66        .finish();
67    tracing::subscriber::set_global_default(subscriber).expect("setting default subscriber failed");
68}