From 16af1c1bd0bdd4e8d5fbe85fd36df23c681b0f8e Mon Sep 17 00:00:00 2001 From: DarkCat09 Date: Mon, 5 Aug 2024 12:04:35 +0400 Subject: [PATCH] refactor/feat: Response::bytes() and text(), rename body->stream --- Cargo.toml | 1 + src/response.rs | 25 ++++++++++++++++++++----- 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 607b167..97d7e29 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,6 +11,7 @@ categories = ["network-programming"] [dependencies] base64ct = "1.6.0" +bytes = "1.7.1" mime = "0.3.17" num_enum = "0.7.3" sha2 = "0.10.8" diff --git a/src/response.rs b/src/response.rs index a4732d0..0da2940 100644 --- a/src/response.rs +++ b/src/response.rs @@ -1,20 +1,23 @@ use crate::{status::Status, LibError}; +use bytes::Bytes; +use tokio::io::AsyncReadExt; + type BodyStream = tokio_rustls::client::TlsStream; #[derive(Debug)] pub struct Response { status: Status, message: String, - body: BodyStream, + stream: BodyStream, } impl Response { - pub fn new(status: Status, message: String, body: BodyStream) -> Self { + pub fn new(status: Status, message: String, stream: BodyStream) -> Self { Response { status, message, - body, + stream, } } @@ -30,7 +33,19 @@ impl Response { self.message.parse().map_err(|e| LibError::InvalidMime(e)) } - pub fn body(self: &mut Self) -> &mut BodyStream { - &mut self.body + pub fn stream(self: &mut Self) -> &mut BodyStream { + &mut self.stream + } + + pub async fn bytes(self: &mut Self) -> Result { + let mut buf = Vec::new(); + self.stream.read_to_end(&mut buf).await?; + Ok(Bytes::from(buf)) + } + + pub async fn text(self: &mut Self) -> Result { + let mut buf = String::new(); + self.stream.read_to_string(&mut buf).await?; + Ok(buf) } }