Advertisement
Guest User

Untitled

a guest
Oct 16th, 2019
155
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rust 1.94 KB | None | 0 0
  1. use futures::{future, Stream};
  2. use hyper::{Body, Method, Request, Response, Server, StatusCode};
  3. use hyper::rt::Future;
  4. use hyper::service::service_fn;
  5.  
  6. type BoxFut = Box<dyn Future<Item=Response<Body>, Error=hyper::Error> + Send>;
  7.  
  8. fn echo(req: Request<Body>) -> BoxFut {
  9.   let mut response = Response::new(Body::empty());
  10.   match (req.method(), req.uri().path()) {
  11.     (&Method::GET, "/") => {
  12.       *response.body_mut() = Body::from("Try POSTing data to /echo");
  13.     },
  14.     (&Method::POST, "/echo") => {
  15.       *response.body_mut() = req.into_body();
  16.     },
  17.     (&Method::POST, "/echo/uppercase") => {
  18.       let mapping = req.into_body()
  19.         .map(|chunk| {
  20.           chunk.iter()
  21.             .map(|byte| byte.to_ascii_uppercase())
  22.             .collect::<Vec<u8>>()
  23.         });
  24.       *response.body_mut() = Body::wrap_stream(mapping);
  25.     },
  26.     // Yet another route inside our match block...
  27.     (&Method::POST, "/echo/reverse") => {
  28.       // This is actually a new `Future`, waiting on `concat`...
  29.       let reversed = req
  30.         .into_body()
  31.         // A future of when we finally have the full body...
  32.         .concat2()
  33.         // `move` the `Response` into this future...
  34.         .map(move |chunk| {
  35.             let body = chunk.iter()
  36.                 .rev()
  37.                 .cloned()
  38.                 .collect::<Vec<u8>>();
  39.             *response.body_mut() = Body::from(body);
  40.             response
  41.         });
  42.       // We can't just return the `Response` from this match arm,
  43.       // because we can't set the body until the `concat` future
  44.       // completed...
  45.       //
  46.       // However, `reversed` is actually a `Future` that will return
  47.       // a `Response`! So, let's return it immediately instead of
  48.       // falling through to the default return of this function.
  49.       return Box::new(reversed)
  50.     },
  51.     _ => {
  52.       *response.status_mut() = StatusCode::NOT_FOUND;
  53.     },
  54.   }
  55.   Box::new(future::ok(response))
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement