http: implement HttpClient for SimpleHttp

Signed-off-by: Fabian Grünbichler <f.gruenbichler@proxmox.com>
This commit is contained in:
Fabian Grünbichler 2022-06-23 11:57:25 +02:00
parent 3c0486be50
commit bd1f9f103e
3 changed files with 70 additions and 4 deletions

View File

@ -23,6 +23,7 @@ tokio = { version = "1.0", features = [], optional = true }
tokio-openssl = { version = "0.6.1", optional = true }
url = { version = "2", optional = true }
proxmox-async = { path = "../proxmox-async", optional = true, version = "0.4.1" }
proxmox-sys = { path = "../proxmox-sys", optional = true, version = "0.3.0" }
proxmox-io = { path = "../proxmox-io", optional = true, version = "1.0.0" }
proxmox-lang = { path = "../proxmox-lang", optional = true, version = "1.1" }

View File

@ -146,9 +146,26 @@ impl SimpleHttp {
}
pub async fn response_body_string(res: Response<Body>) -> Result<String, Error> {
let buf = hyper::body::to_bytes(res).await?;
String::from_utf8(buf.to_vec())
.map_err(|err| format_err!("Error converting HTTP result data: {}", err))
Self::convert_body_to_string(Ok(res))
.await
.map(|res| res.into_body())
}
async fn convert_body_to_string(
response: Result<Response<Body>, Error>,
) -> Result<Response<String>, Error> {
match response {
Ok(res) => {
let (parts, body) = res.into_parts();
let buf = hyper::body::to_bytes(body).await?;
let new_body = String::from_utf8(buf.to_vec())
.map_err(|err| format_err!("Error converting HTTP result data: {}", err))?;
Ok(Response::from_parts(parts, new_body))
}
Err(err) => Err(err),
}
}
}
@ -157,3 +174,51 @@ impl Default for SimpleHttp {
Self::new()
}
}
#[cfg(all(feature = "client-trait", feature = "proxmox-async"))]
impl crate::HttpClient<Body> for SimpleHttp {
fn get(&self, uri: &str) -> Result<Response<Body>, Error> {
let req = Request::builder()
.method("GET")
.uri(uri)
.body(Body::empty())?;
proxmox_async::runtime::block_on(self.request(req))
}
fn post(
&self,
uri: &str,
body: Option<&str>,
content_type: Option<&str>,
) -> Result<Response<Body>, Error> {
proxmox_async::runtime::block_on(self.post(uri, body.map(|s| s.to_owned()), content_type))
}
}
#[cfg(all(feature = "client-trait", feature = "proxmox-async"))]
impl crate::HttpClient<String> for SimpleHttp {
fn get(&self, uri: &str) -> Result<Response<String>, Error> {
let req = Request::builder()
.method("GET")
.uri(uri)
.body(Body::empty())?;
proxmox_async::runtime::block_on(async move {
Self::convert_body_to_string(self.request(req).await).await
})
}
fn post(
&self,
uri: &str,
body: Option<&str>,
content_type: Option<&str>,
) -> Result<Response<String>, Error> {
proxmox_async::runtime::block_on(async move {
Self::convert_body_to_string(
self.post(uri, body.map(|s| s.to_owned()), content_type)
.await,
)
.await
})
}
}

View File

@ -7,7 +7,7 @@ pub trait HttpClient<T> {
fn post(
&self,
uri: &str,
body: Option<String>,
body: Option<&str>,
content_type: Option<&str>,
) -> Result<Response<T>, Error>;
}