diff options
-rw-r--r-- | Cargo.toml | 1 | ||||
-rw-r--r-- | src/lib.rs | 42 |
2 files changed, 26 insertions, 17 deletions
@@ -21,6 +21,7 @@ authors = ["haraldei"] [dependencies] reqwest = "0.8" +serde = "1.0" [dev-dependencies] dotenv = "0.13" @@ -15,12 +15,14 @@ // along with this program. If not, see <https://www.gnu.org/licenses/>. extern crate reqwest; +extern crate serde; use reqwest::{ header::{Accept, ContentType, qitem}, mime, StatusCode, }; +use serde::Serialize; use std::io::Read; const ZOTAPI_CHANNEL_STREAM_PATH : &str = "/api/z/1.0/channel/stream"; @@ -65,23 +67,7 @@ impl<'a> ItemBuilder<'a> { } pub fn create(&self) -> Result<String, Error> { - let url = self.client.url(ZOTAPI_ITEM_UPDATE_PATH); - let mut res = self.client.inner.post(&url) - .header(Accept(vec![qitem(mime::APPLICATION_JSON)])) - .header(ContentType::form_url_encoded()) - .basic_auth(self.client.user.clone(), Some(self.client.pw.clone())) - .form(&[("body", self.body)]) - .send()?; - - match res.status() { - StatusCode::Unauthorized => Err(Error::Unauthorized), - StatusCode::Ok => { - let mut body = String::new(); - res.read_to_string(&mut body)?; - Ok(body) - }, - _ => Err(Error::Unknown) - } + self.client.post_data(ZOTAPI_ITEM_UPDATE_PATH, &[("body", self.body)]) } } @@ -126,6 +112,28 @@ impl Client { _ => Err(Error::Unknown) } } + + fn post_data<T>(&self, path: &str, data: &T) -> Result<String, Error> + where T: Serialize, + { + let url = self.url(path); + let mut res = self.inner.post(&url) + .header(Accept(vec![qitem(mime::APPLICATION_JSON)])) + .header(ContentType::form_url_encoded()) + .basic_auth(self.user.clone(), Some(self.pw.clone())) + .form(&data) + .send()?; + + match res.status() { + StatusCode::Unauthorized => Err(Error::Unauthorized), + StatusCode::Ok => { + let mut body = String::new(); + res.read_to_string(&mut body)?; + Ok(body) + }, + _ => Err(Error::Unknown) + } + } } pub fn client(url: &str, user: &str, pw: &str) -> Client |