Skip to content

Commit 3eeb898

Browse files
committed
Body::from_file takes a Path
1 parent 1d15c83 commit 3eeb898

File tree

1 file changed

+14
-12
lines changed

1 file changed

+14
-12
lines changed

src/body.rs

Lines changed: 14 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
1+
use async_std::fs;
12
use async_std::io::prelude::*;
23
use async_std::io::{self, Cursor};
34
use serde::{de::DeserializeOwned, Serialize};
45

56
use std::fmt::{self, Debug};
7+
use std::path::Path;
68
use std::pin::Pin;
79
use std::task::{Context, Poll};
810

@@ -182,28 +184,28 @@ impl Body {
182184
Ok(body)
183185
}
184186

185-
/// Create a `Body` from an async-std File.
187+
/// Create a `Body` from a file.
186188
///
187-
/// The Mime type set to `application/octet-stream` if no other mime type has been set or can
188-
/// be sniffed.
189+
/// The Mime type set to `application/octet-stream` if no other mime type has
190+
/// been set or can be sniffed.
189191
///
190192
/// # Examples
191193
///
192194
/// ```no_run
195+
/// # fn main() -> Result<(), http_types::Error> { async_std::task::block_on(async {
193196
/// use http_types::{Body, Response, StatusCode};
194-
/// use async_std::fs::File;
195197
///
196-
/// # async_std::task::block_on(async {
197198
/// 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-
/// # });
199+
/// res.set_body(Body::from_file("/path/to/file").await?);
200+
/// # Ok(()) }) }
203201
/// ```
204202
#[cfg(feature = "async_std")]
205-
pub fn from_file(file: async_std::fs::File) -> Self {
206-
file.into()
203+
pub async fn from_file<P>(file: P) -> io::Result<Self>
204+
where
205+
P: AsRef<Path>,
206+
{
207+
let file = fs::read(file.as_ref()).await?;
208+
Ok(file.into())
207209
}
208210

209211
/// Get the length of the body in bytes.

0 commit comments

Comments
 (0)