You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
49 lines
1.5 KiB
49 lines
1.5 KiB
3 years ago
|
use reqwest::{Client, RequestBuilder, Url};
|
||
|
use serde::Serialize;
|
||
|
use serde_json::{from_str, json, Value};
|
||
|
|
||
|
const SERVER: &str = "u_server";
|
||
|
const PORT: &str = "63714";
|
||
|
|
||
|
pub struct AgentClient {
|
||
|
client: Client,
|
||
|
base_url: Url,
|
||
|
}
|
||
|
|
||
|
impl AgentClient {
|
||
|
pub fn new() -> Self {
|
||
|
Self {
|
||
|
client: Client::new(),
|
||
|
base_url: Url::parse(&format!("http://{}:{}", SERVER, PORT)).unwrap(),
|
||
|
}
|
||
|
}
|
||
|
|
||
|
async fn process_request(&self, req: RequestBuilder, resp_needed: bool) -> Value {
|
||
|
let resp = req.send().await.unwrap();
|
||
|
if let Err(e) = resp.error_for_status_ref() {
|
||
|
panic!(
|
||
|
"Server responded with code {}\nError: {}",
|
||
|
e.status()
|
||
|
.map(|s| s.to_string())
|
||
|
.unwrap_or(String::from("<none>")),
|
||
|
e.to_string()
|
||
|
);
|
||
|
}
|
||
|
if !resp_needed {
|
||
|
return json!([]);
|
||
|
}
|
||
|
let resp: Value = from_str(&resp.text().await.unwrap()).unwrap();
|
||
|
resp.get("inner").unwrap().get(0).unwrap().clone()
|
||
|
}
|
||
|
|
||
|
pub async fn get<S: AsRef<str>>(&self, url: S) -> Value {
|
||
|
let req = self.client.get(self.base_url.join(url.as_ref()).unwrap());
|
||
|
self.process_request(req, true).await
|
||
|
}
|
||
|
|
||
|
pub async fn post<S: AsRef<str>, B: Serialize>(&self, url: S, body: &B) -> Value {
|
||
|
let req = self.client.post(self.base_url.join(url.as_ref()).unwrap());
|
||
|
self.process_request(req.json(body), false).await
|
||
|
}
|
||
|
}
|