Skip to content

Commit 86223b9

Browse files
committed
Set Content-Length if we can
1 parent 964adfb commit 86223b9

File tree

2 files changed

+13
-2
lines changed

2 files changed

+13
-2
lines changed

src/isahc.rs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,10 @@ impl HttpClient for IsahcClient {
4242
let client = self.client.clone();
4343
Box::pin(async move {
4444
let (parts, body) = req.into_parts();
45-
let body = isahc::Body::reader(body);
45+
let body = match body.len {
46+
Some(len) => isahc::Body::reader_sized(body, len),
47+
None => isahc::Body::reader(body),
48+
};
4649
let req: http::Request<isahc::Body> = http::Request::from_parts(parts, body);
4750

4851
let res = client.send_async(req).await?;

src/lib.rs

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,20 +70,26 @@ pub trait HttpClient: Debug + Unpin + Send + Sync + Clone + 'static {
7070
/// like `Vec<u8>` or `String`, using the `From` trait.
7171
pub struct Body {
7272
reader: Box<dyn AsyncRead + Unpin + Send + 'static>,
73+
/// Intentionally use `u64` over `usize` here.
74+
/// `usize` won't work if you try to send 10GB file from 32bit host.
75+
#[allow(dead_code)] // not all backends make use of this
76+
len: Option<u64>,
7377
}
7478

7579
impl Body {
7680
/// Create a new empty body.
7781
pub fn empty() -> Self {
7882
Self {
7983
reader: Box::new(futures::io::empty()),
84+
len: Some(0),
8085
}
8186
}
8287

8388
/// Create a new instance from a reader.
8489
pub fn from_reader(reader: impl AsyncRead + Unpin + Send + 'static) -> Self {
8590
Self {
8691
reader: Box::new(reader),
92+
len: None,
8793
}
8894
}
8995
}
@@ -110,8 +116,10 @@ impl From<Vec<u8>> for Body {
110116
#[allow(missing_doc_code_examples)]
111117
#[inline]
112118
fn from(vec: Vec<u8>) -> Body {
119+
let len = vec.len() as u64;
113120
Self {
114121
reader: Box::new(Cursor::new(vec)),
122+
len: Some(len),
115123
}
116124
}
117125
}
@@ -120,6 +128,6 @@ impl<R: AsyncRead + Unpin + Send + 'static> From<Box<R>> for Body {
120128
/// Converts an `AsyncRead` into a Body.
121129
#[allow(missing_doc_code_examples)]
122130
fn from(reader: Box<R>) -> Self {
123-
Self { reader }
131+
Self { reader, len: None }
124132
}
125133
}

0 commit comments

Comments
 (0)