Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Automatically insert Content-Length header to POST requests #334

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
20 changes: 15 additions & 5 deletions src/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(())
}

Expand All @@ -325,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.
Expand All @@ -334,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.
Expand All @@ -352,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::path::Path>) -> 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(())
}

Expand All @@ -366,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(())
}

Expand Down