server.rs 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. extern crate futures;
  2. extern crate hyper;
  3. use futures::future;
  4. use hyper::rt::Future;
  5. use hyper::service::service_fn;
  6. use hyper::{Body, Method, Request, Response, Server, StatusCode};
  7. type BoxFut = Box<Future<Item = Response<Body>, Error = hyper::Error> + Send>;
  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, "/debug") => {
  15. let mapping = req
  16. .headers()
  17. .iter()
  18. .map(|(name, value)| {
  19. format!("{}: \"{}\"\n", name.as_str(), value.to_str().unwrap())
  20. })
  21. .collect::<Vec<_>>()
  22. .concat();
  23. *response.body_mut() = Body::from(mapping);
  24. }
  25. _ => {
  26. *response.status_mut() = StatusCode::NOT_FOUND;
  27. }
  28. };
  29. Box::new(future::ok(response))
  30. }
  31. fn main() {
  32. let addr = ([127, 0, 0, 1], 3000).into();
  33. let server = Server::bind(&addr)
  34. .serve(|| service_fn(echo))
  35. .map_err(|e| eprintln!("server error: {}", e));
  36. hyper::rt::run(server);
  37. }