From 7f6ef5d2d21d99b34d9a36fedb3df71c250f5c89 Mon Sep 17 00:00:00 2001 From: Yagiz Degirmenci Date: Wed, 8 Dec 2021 22:18:03 +0300 Subject: [PATCH 1/2] feat: automatically insert content-length header with body_json function Signed-off-by: Yagiz Degirmenci --- src/request.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/request.rs b/src/request.rs index bb83500..0c898ba 100644 --- a/src/request.rs +++ b/src/request.rs @@ -315,7 +315,9 @@ impl Request { /// /// This method will return an error if the provided data could not be serialized to JSON. pub fn body_json(&mut self, json: &impl Serialize) -> crate::Result<()> { - self.set_body(Body::from_json(json)?); + let body: Body = Body::from_json(json)?; + self.set_header("Content-Length", body.len().unwrap().to_string()); + self.set_body(body); Ok(()) } From d5ce9414781c8da29fe50e493354d810e7e7aa6d Mon Sep 17 00:00:00 2001 From: Yagiz Degirmenci Date: Wed, 8 Dec 2021 22:31:46 +0300 Subject: [PATCH 2/2] feat: automatically insert content-length Automatically insert the Content-Length header when body_string, body_form, body_file and body_bytes is called Signed-off-by: Yagiz Degirmenci --- src/request.rs | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/src/request.rs b/src/request.rs index 0c898ba..441afd6 100644 --- a/src/request.rs +++ b/src/request.rs @@ -327,7 +327,9 @@ impl Request { /// /// The `content-type` is set to `text/plain; charset=utf-8`. pub fn body_string(&mut self, string: String) { - self.set_body(Body::from_string(string)) + let body: Body = Body::from_string(string); + self.set_header("Content-Length", body.len().unwrap().to_string()); + self.set_body(body) } /// Pass bytes as the request body. @@ -336,7 +338,9 @@ impl Request { /// /// The `content-type` is set to `application/octet-stream`. pub fn body_bytes(&mut self, bytes: impl AsRef<[u8]>) { - self.set_body(Body::from(bytes.as_ref())) + let body: Body = Body::from(bytes.as_ref()); + self.set_header("Content-Length", body.len().unwrap().to_string()); + self.set_body(body) } /// Pass a file as the request body. @@ -354,7 +358,9 @@ impl Request { /// This method will return an error if the file couldn't be read. #[cfg(not(target_arch = "wasm32"))] pub async fn body_file(&mut self, path: impl AsRef) -> std::io::Result<()> { - self.set_body(Body::from_file(path).await?); + let body: Body = Body::from_file(path).await?; + self.set_header("Content-Length", body.len().unwrap().to_string()); + self.set_body(body); Ok(()) } @@ -368,7 +374,9 @@ impl Request { /// /// An error will be returned if the encoding failed. pub fn body_form(&mut self, form: &impl Serialize) -> crate::Result<()> { - self.set_body(Body::from_form(form)?); + let body: Body = Body::from_form(form)?; + self.set_header("Content-Length", body.len().unwrap().to_string()); + self.set_body(body); Ok(()) }