|
| 1 | +use async_std::fs; |
1 | 2 | use async_std::io::prelude::*;
|
2 | 3 | use async_std::io::{self, Cursor};
|
3 | 4 | use serde::{de::DeserializeOwned, Serialize};
|
4 | 5 |
|
5 | 6 | use std::fmt::{self, Debug};
|
| 7 | +use std::path::Path; |
6 | 8 | use std::pin::Pin;
|
7 | 9 | use std::task::{Context, Poll};
|
8 | 10 |
|
@@ -182,28 +184,28 @@ impl Body {
|
182 | 184 | Ok(body)
|
183 | 185 | }
|
184 | 186 |
|
185 |
| - /// Create a `Body` from an async-std File. |
| 187 | + /// Create a `Body` from a file. |
186 | 188 | ///
|
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. |
189 | 191 | ///
|
190 | 192 | /// # Examples
|
191 | 193 | ///
|
192 | 194 | /// ```no_run
|
| 195 | + /// # fn main() -> Result<(), http_types::Error> { async_std::task::block_on(async { |
193 | 196 | /// use http_types::{Body, Response, StatusCode};
|
194 |
| - /// use async_std::fs::File; |
195 | 197 | ///
|
196 |
| - /// # async_std::task::block_on(async { |
197 | 198 | /// 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(()) }) } |
203 | 201 | /// ```
|
204 | 202 | #[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()) |
207 | 209 | }
|
208 | 210 |
|
209 | 211 | /// Get the length of the body in bytes.
|
|
0 commit comments