Skip to content

Commit e8c19fe

Browse files
weihangloseanmonstar
authored andcommitted
docs(examples): update send_file example to async/await
1 parent 524a453 commit e8c19fe

File tree

4 files changed

+83
-80
lines changed

4 files changed

+83
-80
lines changed

Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ num_cpus = "1.0"
5353
pretty_env_logger = "0.3"
5454
spmc = "0.2"
5555
url = "1.0"
56-
#tokio-fs = "0.1"
56+
tokio-fs = { git = "https://github.com/tokio-rs/tokio" }
5757
#tokio-mockstream = "1.1.0"
5858
serde = "1.0"
5959
serde_derive = "1.0"

examples/send_file.rs

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
#![feature(async_await)]
2+
#![deny(warnings)]
3+
4+
use tokio::io::AsyncReadExt;
5+
use tokio_fs::file::File;
6+
7+
use hyper::{Body, Method, Result, Request, Response, Server, StatusCode};
8+
use hyper::service::{make_service_fn, service_fn};
9+
10+
static INDEX: &str = "examples/send_file_index.html";
11+
static INTERNAL_SERVER_ERROR: &[u8] = b"Internal Server Error";
12+
static NOTFOUND: &[u8] = b"Not Found";
13+
14+
#[hyper::rt::main]
15+
async fn main() {
16+
pretty_env_logger::init();
17+
18+
let addr = "127.0.0.1:1337".parse().unwrap();
19+
20+
let make_service = make_service_fn(|_| async {
21+
Ok::<_, hyper::Error>(service_fn(response_examples))
22+
});
23+
24+
let server = Server::bind(&addr)
25+
.serve(make_service);
26+
27+
println!("Listening on http://{}", addr);
28+
29+
if let Err(e) = server.await {
30+
eprintln!("server error: {}", e);
31+
}
32+
}
33+
34+
async fn response_examples(req: Request<Body>) -> Result<Response<Body>> {
35+
match (req.method(), req.uri().path()) {
36+
(&Method::GET, "/") |
37+
(&Method::GET, "/index.html") |
38+
(&Method::GET, "/big_file.html") => {
39+
simple_file_send(INDEX).await
40+
}
41+
(&Method::GET, "/no_file.html") => {
42+
// Test what happens when file cannot be be found
43+
simple_file_send("this_file_should_not_exist.html").await
44+
}
45+
_ => Ok(not_found())
46+
}
47+
}
48+
49+
/// HTTP status code 404
50+
fn not_found() -> Response<Body> {
51+
Response::builder()
52+
.status(StatusCode::NOT_FOUND)
53+
.body(NOTFOUND.into())
54+
.unwrap()
55+
}
56+
57+
/// HTTP status code 500
58+
fn internal_server_error() -> Response<Body> {
59+
Response::builder()
60+
.status(StatusCode::INTERNAL_SERVER_ERROR)
61+
.body(INTERNAL_SERVER_ERROR.into())
62+
.unwrap()
63+
}
64+
65+
async fn simple_file_send(f: &str) -> Result<Response<Body>> {
66+
// Serve a file by asynchronously reading it entirely into memory.
67+
// Uses tokio_fs to open file asynchronously, then tokio::io::AsyncReadExt
68+
// to read into memory asynchronously.
69+
70+
let filename = f.to_string(); // we need to copy for lifetime issues
71+
72+
if let Ok(mut file) = File::open(filename).await {
73+
let mut buf = Vec::new();
74+
if let Ok(_) = file.read_to_end(&mut buf).await {
75+
return Ok(Response::new(buf.into()));
76+
}
77+
78+
return Ok(internal_server_error());
79+
}
80+
81+
return Ok(not_found());
82+
}

examples_disabled/send_file.rs

Lines changed: 0 additions & 79 deletions
This file was deleted.

0 commit comments

Comments
 (0)