diff options
Diffstat (limited to 'src/client.rs')
-rw-r--r-- | src/client.rs | 40 |
1 files changed, 21 insertions, 19 deletions
diff --git a/src/client.rs b/src/client.rs index c681b27..3f43479 100644 --- a/src/client.rs +++ b/src/client.rs @@ -22,6 +22,7 @@ use reqwest::{ }; use serde::Serialize; use std::collections::BTreeMap; +use std::fs::File; use std::io::Read; use url::Url; @@ -56,22 +57,17 @@ impl Client { r.to_string() } - pub fn fetch_stream<T>(&self, path: &str, args: &T) -> Result<String, Error> + pub async fn fetch_stream<T>(&self, path: &str, args: &T) -> Result<String, Error> where T: Serialize + std::fmt::Debug, { let url = dbg!(self.url(path, args)); - let res = self - .inner - .get(&url) - .header(ACCEPT, "application/json") - .basic_auth(self.user.clone(), Some(self.pw.clone())) - .send()?; + let res = self.get(&url).send().await?; - handle_result(res) + handle_result(res).await } - pub fn post_data<T>(&self, path: &str, data: &T) -> Result<String, Error> + pub async fn post_data<T>(&self, path: &str, data: &T) -> Result<String, Error> where T: Serialize + std::fmt::Debug, { @@ -84,12 +80,12 @@ impl Client { .basic_auth(self.user.clone(), Some(self.pw.clone())) .body(serde_qs::to_string(&data)?)) //.form(&data)) - .send()?; + .send().await?; - handle_result(res) + handle_result(res).await } - pub fn post_multipart<T>( + pub async fn post_multipart<T>( &self, path: &str, data: &BTreeMap<&str, T>, @@ -106,7 +102,14 @@ impl Client { } for f in files.iter() { - form = form.file("media", f).unwrap(); + let mut pdata = vec![]; + let path = std::path::Path::new(f); + File::open(path)?.read_to_end(&mut pdata)?; + + let filename = String::from(path.file_name().unwrap().to_str().unwrap()); + let p = reqwest::multipart::Part::bytes(pdata) + .file_name(filename); + form = form.part("media", p); } let res = self @@ -114,9 +117,10 @@ impl Client { .post(&url) .basic_auth(self.user.clone(), Some(self.pw.clone())) .multipart(form) - .send()?; + .send() + .await?; - handle_result(res) + handle_result(res).await } /// Return a RequestBuilder object that's set up with the correct @@ -139,13 +143,11 @@ impl Client { // A common function for handling the response after a request. // // Consumes the response, and return it as a string or an error. -fn handle_result(mut res: reqwest::Response) -> Result<String, Error> { +async fn handle_result(res: reqwest::Response) -> Result<String, Error> { match res.status() { StatusCode::UNAUTHORIZED => Err(Error::Unauthorized), StatusCode::OK => { - let mut body = String::new(); - res.read_to_string(&mut body)?; - Ok(body) + Ok(res.text().await?) } _ => { eprintln!("Received unknown status: {:?}", res.status()); |