Skip to content

Commit 0c84cf9

Browse files
jbryoshuawuyts
authored andcommitted
Add From<File> for Body
within async_std feature flag
1 parent b5e2110 commit 0c84cf9

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

src/body.rs

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -182,6 +182,30 @@ impl Body {
182182
Ok(body)
183183
}
184184

185+
/// Create a `Body` from an async-std File.
186+
///
187+
/// The Mime type set to `application/octet-stream` if no other mime type has been set or can
188+
/// be sniffed.
189+
///
190+
/// # Examples
191+
///
192+
/// ```no_run
193+
/// use http_types::{Body, Response, StatusCode};
194+
/// use async_std::fs::File;
195+
///
196+
/// # async_std::task::block_on(async {
197+
/// let mut res = Response::new(StatusCode::Ok);
198+
/// let file = File::open("/path/to/file").await.unwrap();
199+
/// res.set_body(Body::from_file(file));
200+
/// // or
201+
/// res.set_body(File::open("/path/to/file").await.unwrap());
202+
/// # });
203+
/// ```
204+
#[cfg(feature = "async_std")]
205+
pub fn from_file(file: async_std::fs::File) -> Self {
206+
file.into()
207+
}
208+
185209
/// Get the length of the body in bytes.
186210
///
187211
/// # Examples
@@ -322,6 +346,24 @@ impl<'a> From<&'a [u8]> for Body {
322346
}
323347
}
324348

349+
#[cfg(feature = "async_std")]
350+
impl From<async_std::fs::File> for Body {
351+
fn from(file: async_std::fs::File) -> Self {
352+
let length = async_std::task::block_on(async {
353+
file.metadata()
354+
.await
355+
.expect("unable to read file metadata")
356+
.len()
357+
});
358+
359+
Self {
360+
length: Some(length as usize),
361+
reader: Box::new(async_std::io::BufReader::new(file)),
362+
mime: mime::BYTE_STREAM,
363+
}
364+
}
365+
}
366+
325367
impl Read for Body {
326368
#[allow(missing_doc_code_examples)]
327369
fn poll_read(

0 commit comments

Comments
 (0)