Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use futures::{future, Stream};
- use hyper::{Body, Method, Request, Response, Server, StatusCode};
- use hyper::rt::Future;
- use hyper::service::service_fn;
- type BoxFut = Box<dyn Future<Item=Response<Body>, Error=hyper::Error> + Send>;
- fn echo(req: Request<Body>) -> BoxFut {
- let mut response = Response::new(Body::empty());
- match (req.method(), req.uri().path()) {
- (&Method::GET, "/") => {
- *response.body_mut() = Body::from("Try POSTing data to /echo");
- },
- (&Method::POST, "/echo") => {
- *response.body_mut() = req.into_body();
- },
- (&Method::POST, "/echo/uppercase") => {
- let mapping = req.into_body()
- .map(|chunk| {
- chunk.iter()
- .map(|byte| byte.to_ascii_uppercase())
- .collect::<Vec<u8>>()
- });
- *response.body_mut() = Body::wrap_stream(mapping);
- },
- // Yet another route inside our match block...
- (&Method::POST, "/echo/reverse") => {
- // This is actually a new `Future`, waiting on `concat`...
- let reversed = req
- .into_body()
- // A future of when we finally have the full body...
- .concat2()
- // `move` the `Response` into this future...
- .map(move |chunk| {
- let body = chunk.iter()
- .rev()
- .cloned()
- .collect::<Vec<u8>>();
- *response.body_mut() = Body::from(body);
- response
- });
- // We can't just return the `Response` from this match arm,
- // because we can't set the body until the `concat` future
- // completed...
- //
- // However, `reversed` is actually a `Future` that will return
- // a `Response`! So, let's return it immediately instead of
- // falling through to the default return of this function.
- return Box::new(reversed)
- },
- _ => {
- *response.status_mut() = StatusCode::NOT_FOUND;
- },
- }
- Box::new(future::ok(response))
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement