|
| 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 | +} |
0 commit comments