proxctl_bindings/api/
http_client.rs1use reqwest::{
2 header::{HeaderMap, HeaderValue},
3 Client as ReqwestClient,
4};
5use serde::Serialize;
6
7pub struct Client {
8 client: ReqwestClient,
9 base_url: String,
10 pub api_token: Option<String>,
11 pub csrf_token: Option<String>,
12}
13
14impl Client {
15 pub fn new(base_url: String) -> Self {
16 let mut headers = HeaderMap::new();
17 headers.insert("Accept", HeaderValue::from_static("application/json"));
18 headers.insert("Content-Type", HeaderValue::from_static("application/json"));
19
20 let client = ReqwestClient::builder()
21 .danger_accept_invalid_certs(true)
22 .default_headers(headers)
23 .build()
24 .expect("Failed to create HTTP client");
25
26 Self {
27 client,
28 base_url,
29 api_token: None,
30 csrf_token: None,
31 }
32 }
33
34 pub fn set_tokens(&mut self, ticket: String, csrf_token: Option<String>) {
35 let cookie = format!("PVEAuthCookie={}", ticket);
36 self.client = ReqwestClient::builder()
37 .danger_accept_invalid_certs(true)
38 .default_headers({
39 let mut headers = HeaderMap::new();
40 headers.insert("Accept", HeaderValue::from_static("application/json"));
41 headers.insert("Content-Type", HeaderValue::from_static("application/json"));
42 headers.insert("Cookie", HeaderValue::from_str(&cookie).unwrap());
43 headers
44 })
45 .build()
46 .expect("Failed to create HTTP client");
47
48 self.api_token = Some(ticket);
49 self.csrf_token = csrf_token;
50 }
51
52 pub async fn get(&self, path: &str) -> Result<reqwest::Response, reqwest::Error> {
53 let url = format!("{}{}", self.base_url, path);
54 let req = self.client.get(&url);
55 req.send().await
56 }
57
58 pub async fn post<T>(&self, path: &str, body: &T) -> Result<reqwest::Response, reqwest::Error>
59 where
60 T: Serialize,
61 {
62 let url = format!("{}{}", self.base_url, path);
63 let mut req = self.client.post(&url).json(body);
64
65 if let Some(csrf) = &self.csrf_token {
66 req = req.header("CSRFPreventionToken", csrf);
67 }
68
69 req.send().await
70 }
71}