feat(service): introduce hyper-specific Service
This introduces the `hyper::service` module, which replaces `tokio-service`. Since the trait is specific to hyper, its associated types have been adjusted. It didn't make sense to need to define `Service<Request=http::Request>`, since we already know the context is HTTP. Instead, the request and response bodies are associated types now, and slightly stricter bounds have been placed on `Error`. The helpers `service_fn` and `service_fn_ok` should be sufficient for now to ease creating `Service`s. The `NewService` trait now allows service creation to also be asynchronous. These traits are similar to `tower` in nature, and possibly will be replaced completely by it in the future. For now, hyper defining its own allows the traits to have better context, and prevents breaking changes in `tower` from affecting hyper. Closes #1461 BREAKING CHANGE: The `Service` trait has changed: it has some changed associated types, and `call` is now bound to `&mut self`. The `NewService` trait has changed: it has some changed associated types, and `new_service` now returns a `Future`. `Client` no longer implements `Service` for now. `hyper::server::conn::Serve` now returns `Connecting` instead of `Connection`s, since `new_service` can now return a `Future`. The `Connecting` is a future wrapping the new service future, returning a `Connection` afterwards. In many cases, `Future::flatten` can be used.
This commit is contained in:
@@ -4,11 +4,11 @@ extern crate hyper;
|
||||
extern crate pretty_env_logger;
|
||||
extern crate tokio;
|
||||
|
||||
use futures::{Future/*, Sink*/};
|
||||
use futures::{future, Future};
|
||||
use futures::sync::oneshot;
|
||||
|
||||
use hyper::{Body, /*Chunk,*/ Method, Request, Response, StatusCode};
|
||||
use hyper::server::{Server, Service};
|
||||
use hyper::{Body, Method, Request, Response, Server, StatusCode};
|
||||
use hyper::service::service_fn;
|
||||
|
||||
use std::fs::File;
|
||||
use std::io::{self, copy/*, Read*/};
|
||||
@@ -17,7 +17,92 @@ use std::thread;
|
||||
static NOTFOUND: &[u8] = b"Not Found";
|
||||
static INDEX: &str = "examples/send_file_index.html";
|
||||
|
||||
fn simple_file_send(f: &str) -> Box<Future<Item = Response<Body>, Error = io::Error> + Send> {
|
||||
|
||||
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);
|
||||
|
||||
tokio::run(server);
|
||||
}
|
||||
|
||||
type ResponseFuture = Box<Future<Item=Response<Body>, Error=io::Error> + Send>;
|
||||
|
||||
fn response_examples(req: Request<Body>) -> ResponseFuture {
|
||||
match (req.method(), req.uri().path()) {
|
||||
(&Method::GET, "/") | (&Method::GET, "/index.html") => {
|
||||
simple_file_send(INDEX)
|
||||
},
|
||||
(&Method::GET, "/big_file.html") => {
|
||||
// Stream a large file in chunks. This requires a
|
||||
// little more overhead with two channels, (one for
|
||||
// the response future, and a second for the response
|
||||
// body), but can handle arbitrarily large files.
|
||||
//
|
||||
// We use an artificially small buffer, since we have
|
||||
// a small test file.
|
||||
let (tx, rx) = oneshot::channel();
|
||||
thread::spawn(move || {
|
||||
let _file = match File::open(INDEX) {
|
||||
Ok(f) => f,
|
||||
Err(_) => {
|
||||
tx.send(Response::builder()
|
||||
.status(StatusCode::NOT_FOUND)
|
||||
.body(NOTFOUND.into())
|
||||
.unwrap())
|
||||
.expect("Send error on open");
|
||||
return;
|
||||
},
|
||||
};
|
||||
let (_tx_body, rx_body) = Body::channel();
|
||||
let res = Response::new(rx_body.into());
|
||||
tx.send(res).expect("Send error on successful file read");
|
||||
/* TODO: fix once we have futures 0.2 Sink working
|
||||
let mut buf = [0u8; 16];
|
||||
loop {
|
||||
match file.read(&mut buf) {
|
||||
Ok(n) => {
|
||||
if n == 0 {
|
||||
// eof
|
||||
tx_body.close().expect("panic closing");
|
||||
break;
|
||||
} else {
|
||||
let chunk: Chunk = buf[0..n].to_vec().into();
|
||||
match tx_body.send_data(chunk).wait() {
|
||||
Ok(t) => { tx_body = t; },
|
||||
Err(_) => { break; }
|
||||
};
|
||||
}
|
||||
},
|
||||
Err(_) => { break; }
|
||||
}
|
||||
}
|
||||
*/
|
||||
});
|
||||
|
||||
Box::new(rx.map_err(|e| io::Error::new(io::ErrorKind::Other, e)))
|
||||
},
|
||||
(&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 reading it entirely into memory. As a result
|
||||
// this is limited to serving small files, but it is somewhat
|
||||
// simpler with a little less overhead.
|
||||
@@ -57,94 +142,3 @@ fn simple_file_send(f: &str) -> Box<Future<Item = Response<Body>, Error = io::Er
|
||||
Box::new(rx.map_err(|e| io::Error::new(io::ErrorKind::Other, e)))
|
||||
}
|
||||
|
||||
struct ResponseExamples;
|
||||
|
||||
impl Service for ResponseExamples {
|
||||
type Request = Request<Body>;
|
||||
type Response = Response<Body>;
|
||||
type Error = io::Error;
|
||||
type Future = Box<Future<Item = Self::Response, Error = Self::Error> + Send>;
|
||||
|
||||
fn call(&self, req: Request<Body>) -> Self::Future {
|
||||
match (req.method(), req.uri().path()) {
|
||||
(&Method::GET, "/") | (&Method::GET, "/index.html") => {
|
||||
simple_file_send(INDEX)
|
||||
},
|
||||
(&Method::GET, "/big_file.html") => {
|
||||
// Stream a large file in chunks. This requires a
|
||||
// little more overhead with two channels, (one for
|
||||
// the response future, and a second for the response
|
||||
// body), but can handle arbitrarily large files.
|
||||
//
|
||||
// We use an artificially small buffer, since we have
|
||||
// a small test file.
|
||||
let (tx, rx) = oneshot::channel();
|
||||
thread::spawn(move || {
|
||||
let _file = match File::open(INDEX) {
|
||||
Ok(f) => f,
|
||||
Err(_) => {
|
||||
tx.send(Response::builder()
|
||||
.status(StatusCode::NOT_FOUND)
|
||||
.body(NOTFOUND.into())
|
||||
.unwrap())
|
||||
.expect("Send error on open");
|
||||
return;
|
||||
},
|
||||
};
|
||||
let (_tx_body, rx_body) = Body::channel();
|
||||
let res = Response::new(rx_body.into());
|
||||
tx.send(res).expect("Send error on successful file read");
|
||||
/* TODO: fix once we have futures 0.2 Sink working
|
||||
let mut buf = [0u8; 16];
|
||||
loop {
|
||||
match file.read(&mut buf) {
|
||||
Ok(n) => {
|
||||
if n == 0 {
|
||||
// eof
|
||||
tx_body.close().expect("panic closing");
|
||||
break;
|
||||
} else {
|
||||
let chunk: Chunk = buf[0..n].to_vec().into();
|
||||
match tx_body.send_data(chunk).wait() {
|
||||
Ok(t) => { tx_body = t; },
|
||||
Err(_) => { break; }
|
||||
};
|
||||
}
|
||||
},
|
||||
Err(_) => { break; }
|
||||
}
|
||||
}
|
||||
*/
|
||||
});
|
||||
|
||||
Box::new(rx.map_err(|e| io::Error::new(io::ErrorKind::Other, e)))
|
||||
},
|
||||
(&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(futures::future::ok(Response::builder()
|
||||
.status(StatusCode::NOT_FOUND)
|
||||
.body(Body::empty())
|
||||
.unwrap()))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
fn main() {
|
||||
pretty_env_logger::init();
|
||||
|
||||
let addr = "127.0.0.1:1337".parse().unwrap();
|
||||
|
||||
let server = Server::bind(&addr)
|
||||
.serve(|| Ok(ResponseExamples))
|
||||
.map_err(|e| eprintln!("server error: {}", e));
|
||||
|
||||
println!("Listening on http://{}", addr);
|
||||
|
||||
tokio::run(server);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user