feat(server): add const_service and service_fn helpers
- `const_service` creates a `NewService` that clones references to the wrapped service. - `service_fn` creates a `Service` from a function. Useful with closures.
This commit is contained in:
@@ -3,35 +3,23 @@ extern crate hyper;
|
||||
extern crate futures;
|
||||
extern crate pretty_env_logger;
|
||||
|
||||
use futures::future::FutureResult;
|
||||
|
||||
use hyper::header::{ContentLength, ContentType};
|
||||
use hyper::server::{Http, Service, Request, Response};
|
||||
use hyper::server::{Http, Response, const_service, service_fn};
|
||||
|
||||
static PHRASE: &'static [u8] = b"Hello World!";
|
||||
|
||||
struct Hello;
|
||||
|
||||
impl Service for Hello {
|
||||
type Request = Request;
|
||||
type Response = Response;
|
||||
type Error = hyper::Error;
|
||||
type Future = FutureResult<Response, hyper::Error>;
|
||||
fn call(&self, _req: Request) -> Self::Future {
|
||||
futures::future::ok(
|
||||
Response::new()
|
||||
.with_header(ContentLength(PHRASE.len() as u64))
|
||||
.with_header(ContentType::plaintext())
|
||||
.with_body(PHRASE)
|
||||
)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
fn main() {
|
||||
pretty_env_logger::init().unwrap();
|
||||
let addr = "127.0.0.1:3000".parse().unwrap();
|
||||
let mut server = Http::new().bind(&addr, || Ok(Hello)).unwrap();
|
||||
let addr = ([127, 0, 0, 1], 3000).into();
|
||||
|
||||
let new_service = const_service(service_fn(|_| {
|
||||
Ok(Response::<hyper::Body>::new()
|
||||
.with_header(ContentLength(PHRASE.len() as u64))
|
||||
.with_header(ContentType::plaintext())
|
||||
.with_body(PHRASE))
|
||||
}));
|
||||
|
||||
let mut server = Http::new().bind(&addr, new_service).unwrap();
|
||||
server.no_proto();
|
||||
println!("Listening on http://{} with 1 thread.", server.local_addr().unwrap());
|
||||
server.run().unwrap();
|
||||
|
||||
Reference in New Issue
Block a user