diff --git a/Cargo.toml b/Cargo.toml index edec910c..5b5a21c3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -53,7 +53,7 @@ num_cpus = "1.0" pretty_env_logger = "0.3" spmc = "0.2" url = "1.0" -#tokio-fs = "0.1" +tokio-fs = { git = "https://github.com/tokio-rs/tokio" } #tokio-mockstream = "1.1.0" serde = "1.0" serde_derive = "1.0" diff --git a/examples/send_file.rs b/examples/send_file.rs new file mode 100644 index 00000000..1e59d891 --- /dev/null +++ b/examples/send_file.rs @@ -0,0 +1,82 @@ +#![feature(async_await)] +#![deny(warnings)] + +use tokio::io::AsyncReadExt; +use tokio_fs::file::File; + +use hyper::{Body, Method, Result, Request, Response, Server, StatusCode}; +use hyper::service::{make_service_fn, service_fn}; + +static INDEX: &str = "examples/send_file_index.html"; +static INTERNAL_SERVER_ERROR: &[u8] = b"Internal Server Error"; +static NOTFOUND: &[u8] = b"Not Found"; + +#[hyper::rt::main] +async fn main() { + pretty_env_logger::init(); + + let addr = "127.0.0.1:1337".parse().unwrap(); + + let make_service = make_service_fn(|_| async { + Ok::<_, hyper::Error>(service_fn(response_examples)) + }); + + let server = Server::bind(&addr) + .serve(make_service); + + println!("Listening on http://{}", addr); + + if let Err(e) = server.await { + eprintln!("server error: {}", e); + } +} + +async fn response_examples(req: Request) -> Result> { + match (req.method(), req.uri().path()) { + (&Method::GET, "/") | + (&Method::GET, "/index.html") | + (&Method::GET, "/big_file.html") => { + simple_file_send(INDEX).await + } + (&Method::GET, "/no_file.html") => { + // Test what happens when file cannot be be found + simple_file_send("this_file_should_not_exist.html").await + } + _ => Ok(not_found()) + } +} + +/// HTTP status code 404 +fn not_found() -> Response { + Response::builder() + .status(StatusCode::NOT_FOUND) + .body(NOTFOUND.into()) + .unwrap() +} + +/// HTTP status code 500 +fn internal_server_error() -> Response { + Response::builder() + .status(StatusCode::INTERNAL_SERVER_ERROR) + .body(INTERNAL_SERVER_ERROR.into()) + .unwrap() +} + +async fn simple_file_send(f: &str) -> Result> { + // Serve a file by asynchronously reading it entirely into memory. + // Uses tokio_fs to open file asynchronously, then tokio::io::AsyncReadExt + // to read into memory asynchronously. + + let filename = f.to_string(); // we need to copy for lifetime issues + + if let Ok(mut file) = File::open(filename).await { + let mut buf = Vec::new(); + if let Ok(_) = file.read_to_end(&mut buf).await { + return Ok(Response::new(buf.into())); + } + + return Ok(internal_server_error()); + } + + return Ok(not_found()); +} diff --git a/examples_disabled/send_file_index.html b/examples/send_file_index.html similarity index 100% rename from examples_disabled/send_file_index.html rename to examples/send_file_index.html diff --git a/examples_disabled/send_file.rs b/examples_disabled/send_file.rs deleted file mode 100644 index 08c30513..00000000 --- a/examples_disabled/send_file.rs +++ /dev/null @@ -1,79 +0,0 @@ -#![deny(warnings)] -extern crate futures; -extern crate hyper; -extern crate pretty_env_logger; -extern crate tokio_fs; -extern crate tokio_io; - -use futures::{future, Future}; - -use hyper::{Body, Method, Request, Response, Server, StatusCode}; -use hyper::service::service_fn; - -use std::io; - -static NOTFOUND: &[u8] = b"Not Found"; -static INDEX: &str = "examples/send_file_index.html"; - - -fn main() { - pretty_env_logger::init(); - - let addr = "127.0.0.1:1337".parse().unwrap(); - - let server = Server::bind(&addr) - .serve(|| service_fn(response_examples)) - .map_err(|e| eprintln!("server error: {}", e)); - - println!("Listening on http://{}", addr); - - hyper::rt::run(server); -} - -type ResponseFuture = Box, Error=io::Error> + Send>; - -fn response_examples(req: Request) -> ResponseFuture { - match (req.method(), req.uri().path()) { - (&Method::GET, "/") | (&Method::GET, "/index.html") | (&Method::GET, "/big_file.html") => { - simple_file_send(INDEX) - }, - (&Method::GET, "/no_file.html") => { - // Test what happens when file cannot be be found - simple_file_send("this_file_should_not_exist.html") - }, - _ => { - Box::new(future::ok(Response::builder() - .status(StatusCode::NOT_FOUND) - .body(Body::empty()) - .unwrap())) - } - } - -} - -fn simple_file_send(f: &str) -> ResponseFuture { - // Serve a file by asynchronously reading it entirely into memory. - // Uses tokio_fs to open file asynchronously, then tokio_io to read into - // memory asynchronously. - let filename = f.to_string(); // we need to copy for lifetime issues - Box::new(tokio_fs::file::File::open(filename) - .and_then(|file| { - let buf: Vec = Vec::new(); - tokio_io::io::read_to_end(file, buf) - .and_then(|item| { - Ok(Response::new(item.1.into())) - }) - .or_else(|_| { - Ok(Response::builder() - .status(StatusCode::INTERNAL_SERVER_ERROR) - .body(Body::empty()) - .unwrap()) - }) - }) - .or_else(|_| { - Ok(Response::builder() - .status(StatusCode::NOT_FOUND) - .body(NOTFOUND.into()) - .unwrap()) - })) -}