From 2047a9d579a739cfda682601a1af511860a7a722 Mon Sep 17 00:00:00 2001 From: Dirkjan Ochtman Date: Tue, 16 Jul 2024 11:32:02 +0200 Subject: [PATCH] Centralize body extraction --- Cargo.toml | 1 + src/lib.rs | 6 +----- src/types.rs | 17 +++++++---------- 3 files changed, 9 insertions(+), 15 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 33bb5c9..9e144c6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -20,6 +20,7 @@ ring = ["dep:ring", "hyper-rustls?/ring", "rcgen/ring"] [dependencies] aws-lc-rs = { version = "1.8.0", optional = true } base64 = "0.21.0" +bytes = "1" http = "1" http-body-util = "0.1.2" hyper = { version = "1.3.1", features = ["client", "http1", "http2"] } diff --git a/src/lib.rs b/src/lib.rs index e0f5efc..79b9ac0 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -133,11 +133,7 @@ impl Order { .await?; self.nonce = nonce_from_response(&rsp); - let body = Problem::from_response(rsp) - .await? - .collect() - .await? - .to_bytes(); + let body = Problem::from_response(rsp).await?; Ok(Some( String::from_utf8(body.to_vec()) .map_err(|_| "unable to decode certificate as UTF-8")?, diff --git a/src/types.rs b/src/types.rs index 27d9b0e..2f7d16f 100644 --- a/src/types.rs +++ b/src/types.rs @@ -1,6 +1,7 @@ use std::fmt; use base64::prelude::{Engine, BASE64_URL_SAFE_NO_PAD}; +use bytes::Bytes; use http_body_util::BodyExt; use hyper::body::Incoming; use hyper::Response; @@ -134,20 +135,16 @@ pub struct Problem { impl Problem { pub(crate) async fn check(rsp: Response) -> Result { - Ok(serde_json::from_slice( - &Self::from_response(rsp).await?.collect().await?.to_bytes(), - )?) + Ok(serde_json::from_slice(&Self::from_response(rsp).await?)?) } - pub(crate) async fn from_response(rsp: Response) -> Result { + pub(crate) async fn from_response(rsp: Response) -> Result { let status = rsp.status(); - let body = rsp.into_body(); - if status.is_informational() || status.is_success() || status.is_redirection() { - return Ok(body); + let body = rsp.into_body().collect().await?.to_bytes(); + match status.is_informational() || status.is_success() || status.is_redirection() { + true => Ok(body), + false => Err(serde_json::from_slice::(&body)?.into()), } - - let body = body.collect().await?.to_bytes(); - Err(serde_json::from_slice::(&body)?.into()) } }