Files
hyper/examples/server.rs
Sean McArthur c4974500ab feat(server): re-design Server as higher-level API
The `hyper::Server` is now a proper higher-level API for running HTTP
servers. There is a related `hyper::server::Builder` type, to construct
a `Server`. All other types (`Http`, `Serve`, etc) were moved into the
"lower-level" `hyper::server::conn` module.

The `Server` is a `Future` representing a listening HTTP server. Options
needed to build one are set on the `Builder`.

As `Server` is just a `Future`, it no longer owns a thread-blocking
executor, and can thus be run next to other servers, clients, or
what-have-you.

Closes #1322
Closes #1263

BREAKING CHANGE: The `Server` is no longer created from `Http::bind`,
  nor is it `run`. It is a `Future` that must be polled by an
  `Executor`.

  The `hyper::server::Http` type has move to
  `hyper::server::conn::Http`.
2018-04-16 14:29:19 -07:00

55 lines
1.3 KiB
Rust

#![deny(warnings)]
extern crate futures;
extern crate hyper;
extern crate pretty_env_logger;
extern crate tokio;
use futures::Future;
use futures::future::{FutureResult};
use hyper::{Body, Method, Request, Response, StatusCode};
use hyper::server::{Server, Service};
static INDEX: &'static [u8] = b"Try POST /echo";
struct Echo;
impl Service for Echo {
type Request = Request<Body>;
type Response = Response<Body>;
type Error = hyper::Error;
type Future = FutureResult<Self::Response, Self::Error>;
fn call(&self, req: Self::Request) -> Self::Future {
futures::future::ok(match (req.method(), req.uri().path()) {
(&Method::GET, "/") | (&Method::POST, "/") => {
Response::new(INDEX.into())
},
(&Method::POST, "/echo") => {
Response::new(req.into_body())
},
_ => {
let mut res = Response::new(Body::empty());
*res.status_mut() = StatusCode::NOT_FOUND;
res
}
})
}
}
fn main() {
pretty_env_logger::init();
let addr = ([127, 0, 0, 1], 1337).into();
let server = Server::bind(&addr)
.serve(|| Ok(Echo))
.map_err(|e| eprintln!("server error: {}", e));
println!("Listening on http://{}", addr);
tokio::run(server);
}