Skip to content

Commit 203621e

Browse files
authored
feat(example): read file by chunks in send_file example (hyperium#2193)
1 parent e08a271 commit 203621e

File tree

4 files changed

+11
-26
lines changed

4 files changed

+11
-26
lines changed

Cargo.toml

+1
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,7 @@ serde_derive = "1.0"
5151
serde_json = "1.0"
5252
tokio = { version = "0.2.2", features = ["fs", "macros", "io-std", "rt-util", "sync", "time", "test-util"] }
5353
tokio-test = "0.2"
54+
tokio-util = { version = "0.3", features = ["codec"] }
5455
tower-util = "0.3"
5556
url = "1.0"
5657

examples/README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ pretty_env_logger = "0.4"
3939

4040
* [`params`](params.rs) - A webserver that accept a form, with a name and a number, checks the parameters are presents and validates the input.
4141

42-
* [`send_file`](send_file.rs) - A server that sends back content of files using tokio_fs to read the files asynchronously.
42+
* [`send_file`](send_file.rs) - A server that sends back content of files using tokio-util to read the files asynchronously.
4343

4444
* [`single_threaded`](single_threaded.rs) - A server only running on 1 thread, so it can make use of `!Send` app state (like an `Rc` counter).
4545

examples/send_file.rs

+8-23
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
11
#![deny(warnings)]
22

33
use tokio::fs::File;
4-
use tokio::io::AsyncReadExt;
4+
5+
use tokio_util::codec::{BytesCodec, FramedRead};
56

67
use hyper::service::{make_service_fn, service_fn};
78
use hyper::{Body, Method, Request, Response, Result, Server, StatusCode};
89

910
static INDEX: &str = "examples/send_file_index.html";
10-
static INTERNAL_SERVER_ERROR: &[u8] = b"Internal Server Error";
1111
static NOTFOUND: &[u8] = b"Not Found";
1212

1313
#[tokio::main]
@@ -30,9 +30,7 @@ async fn main() {
3030

3131
async fn response_examples(req: Request<Body>) -> Result<Response<Body>> {
3232
match (req.method(), req.uri().path()) {
33-
(&Method::GET, "/") | (&Method::GET, "/index.html") | (&Method::GET, "/big_file.html") => {
34-
simple_file_send(INDEX).await
35-
}
33+
(&Method::GET, "/") | (&Method::GET, "/index.html") => simple_file_send(INDEX).await,
3634
(&Method::GET, "/no_file.html") => {
3735
// Test what happens when file cannot be be found
3836
simple_file_send("this_file_should_not_exist.html").await
@@ -49,26 +47,13 @@ fn not_found() -> Response<Body> {
4947
.unwrap()
5048
}
5149

52-
/// HTTP status code 500
53-
fn internal_server_error() -> Response<Body> {
54-
Response::builder()
55-
.status(StatusCode::INTERNAL_SERVER_ERROR)
56-
.body(INTERNAL_SERVER_ERROR.into())
57-
.unwrap()
58-
}
59-
6050
async fn simple_file_send(filename: &str) -> Result<Response<Body>> {
61-
// Serve a file by asynchronously reading it entirely into memory.
62-
// Uses tokio_fs to open file asynchronously, then tokio::io::AsyncReadExt
63-
// to read into memory asynchronously.
64-
65-
if let Ok(mut file) = File::open(filename).await {
66-
let mut buf = Vec::new();
67-
if let Ok(_) = file.read_to_end(&mut buf).await {
68-
return Ok(Response::new(buf.into()));
69-
}
51+
// Serve a file by asynchronously reading it by chunks using tokio-util crate.
7052

71-
return Ok(internal_server_error());
53+
if let Ok(file) = File::open(filename).await {
54+
let stream = FramedRead::new(file, BytesCodec::new());
55+
let body = Body::wrap_stream(stream);
56+
return Ok(Response::new(body));
7257
}
7358

7459
Ok(not_found())

examples/send_file_index.html

+1-2
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,8 @@
33
<title>Hyper responding example</title>
44
</head>
55
<body>
6-
<h1>Hyper responding example</h1>
6+
<h1>Hyper responding example, streamed in chunks</h1>
77
<a href="index.html">index.html</a> Top Level<br>
8-
<a href="big_file.html">big_file.html</a> This page, streamed in chunks<br>
98
<a href="no_file.html">no_file.html</a> A 404 test, the requested file does not exist<br>
109
</body>
1110
</html>

0 commit comments

Comments
 (0)