Skip to content

Commit 1d06b9b

Browse files
sunfishcodebrightly-salty
andcommitted
Add a Body::from_open_file constructor.
This splits a `Body::from_open_file` out from `Body::from_file` so that users who want to use a file opened in a manner other than `File::open` can do so. In particular, this will help users using [`cap_std::fs::Dir::open`] to open files without requiring http-types to have a dependency on `cap_std`. [`cap_std::fs::Dir::open`]: https://docs.rs/cap-std/latest/cap_std/fs/struct.Dir.html#method.open Co-authored-by: brightly-salty <[email protected]>
1 parent 482106b commit 1d06b9b

File tree

1 file changed

+33
-3
lines changed

1 file changed

+33
-3
lines changed

src/body.rs

Lines changed: 33 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -351,8 +351,9 @@ impl Body {
351351

352352
/// Create a `Body` from a file.
353353
///
354-
/// The Mime type set to `application/octet-stream` if no other mime type has
355-
/// been set or can be sniffed.
354+
/// The Mime type is sniffed from the file contents if possible, otherwise
355+
/// it is inferred from the path's extension if possible, otherwise is set
356+
/// to `application/octet-stream`.
356357
///
357358
/// # Examples
358359
///
@@ -370,7 +371,36 @@ impl Body {
370371
P: AsRef<std::path::Path>,
371372
{
372373
let path = path.as_ref();
373-
let mut file = async_std::fs::File::open(path).await?;
374+
let file = async_std::fs::File::open(path).await?;
375+
Self::from_open_file(file, path).await
376+
}
377+
378+
/// Create a `Body` from an already-open file.
379+
///
380+
/// The Mime type is sniffed from the file contents if possible, otherwise
381+
/// it is inferred from the path's extension if possible, otherwise is set
382+
/// to `application/octet-stream`.
383+
///
384+
/// The path here is only used to provide an extension for guessing the Mime
385+
/// type, and may be empty if the path is unknown.
386+
///
387+
/// # Examples
388+
///
389+
/// ```no_run
390+
/// # fn main() -> http_types::Result<()> { async_std::task::block_on(async {
391+
/// use http_types::{Body, Response, StatusCode};
392+
///
393+
/// let mut res = Response::new(StatusCode::Ok);
394+
/// let path = std::path::Path::new("/path/to/file");
395+
/// let file = async_std::fs::File::open(path).await?;
396+
/// res.set_body(Body::from_open_file(file, path).await?);
397+
/// # Ok(()) }) }
398+
/// ```
399+
#[cfg(all(feature = "fs", not(target_os = "unknown")))]
400+
pub async fn from_open_file(
401+
mut file: async_std::fs::File,
402+
path: &std::path::Path,
403+
) -> io::Result<Self> {
374404
let len = file.metadata().await?.len();
375405

376406
// Look at magic bytes first, look at extension second, fall back to

0 commit comments

Comments
 (0)