docs(examples): Update params example to use async await
This commit is contained in:
		| @@ -1,29 +1,28 @@ | |||||||
| #![deny(warnings)] | #![feature(async_await)] | ||||||
| extern crate futures; | // #![deny(warnings)]  // FIXME: https://github.com/rust-lang/rust/issues/62411 | ||||||
| extern crate hyper; | extern crate hyper; | ||||||
| extern crate pretty_env_logger; | extern crate pretty_env_logger; | ||||||
| extern crate url; | extern crate url; | ||||||
|  |  | ||||||
| use futures::{future, Future, Stream}; |  | ||||||
|  |  | ||||||
| use hyper::{Body, Method, Request, Response, Server, StatusCode}; | use hyper::{Body, Method, Request, Response, Server, StatusCode}; | ||||||
| use hyper::service::service_fn; | use hyper::service::{service_fn, make_service_fn}; | ||||||
|  |  | ||||||
| use std::collections::HashMap; | use std::collections::HashMap; | ||||||
| use url::form_urlencoded; | use url::form_urlencoded; | ||||||
|  | use futures_util::TryStreamExt; | ||||||
|  |  | ||||||
| static INDEX: &[u8] = b"<html><body><form action=\"post\" method=\"post\">Name: <input type=\"text\" name=\"name\"><br>Number: <input type=\"text\" name=\"number\"><br><input type=\"submit\"></body></html>"; | static INDEX: &[u8] = b"<html><body><form action=\"post\" method=\"post\">Name: <input type=\"text\" name=\"name\"><br>Number: <input type=\"text\" name=\"number\"><br><input type=\"submit\"></body></html>"; | ||||||
| static MISSING: &[u8] = b"Missing field"; | static MISSING: &[u8] = b"Missing field"; | ||||||
| static NOTNUMERIC: &[u8] = b"Number field is not numeric"; | static NOTNUMERIC: &[u8] = b"Number field is not numeric"; | ||||||
|  |  | ||||||
| // Using service_fn, we can turn this function into a `Service`. | // Using service_fn, we can turn this function into a `Service`. | ||||||
| fn param_example(req: Request<Body>) -> Box<dyn Future<Item=Response<Body>, Error=hyper::Error> + Send> { | async fn param_example(req: Request<Body>) -> Result<Response<Body>, hyper::Error> { | ||||||
|     match (req.method(), req.uri().path()) { |     match (req.method(), req.uri().path()) { | ||||||
|         (&Method::GET, "/") | (&Method::GET, "/post") => { |         (&Method::GET, "/") | (&Method::GET, "/post") => { | ||||||
|             Box::new(future::ok(Response::new(INDEX.into()))) |             Ok(Response::new(INDEX.into())) | ||||||
|         }, |         }, | ||||||
|         (&Method::POST, "/post") => { |         (&Method::POST, "/post") => { | ||||||
|             Box::new(req.into_body().concat2().map(|b| { |             let b = req.into_body().try_concat().await?; | ||||||
|             // Parse the request body. form_urlencoded::parse |             // Parse the request body. form_urlencoded::parse | ||||||
|             // always succeeds, but in general parsing may |             // always succeeds, but in general parsing may | ||||||
|             // fail (for example, an invalid post of json), so |             // fail (for example, an invalid post of json), so | ||||||
| @@ -42,25 +41,25 @@ fn param_example(req: Request<Body>) -> Box<dyn Future<Item=Response<Body>, Erro | |||||||
|             let name = if let Some(n) = params.get("name") { |             let name = if let Some(n) = params.get("name") { | ||||||
|                 n |                 n | ||||||
|             } else { |             } else { | ||||||
|                     return Response::builder() |                 return Ok(Response::builder() | ||||||
|                     .status(StatusCode::UNPROCESSABLE_ENTITY) |                     .status(StatusCode::UNPROCESSABLE_ENTITY) | ||||||
|                     .body(MISSING.into()) |                     .body(MISSING.into()) | ||||||
|                         .unwrap(); |                     .unwrap()); | ||||||
|             }; |             }; | ||||||
|             let number = if let Some(n) = params.get("number") { |             let number = if let Some(n) = params.get("number") { | ||||||
|                 if let Ok(v) = n.parse::<f64>() { |                 if let Ok(v) = n.parse::<f64>() { | ||||||
|                     v |                     v | ||||||
|                 } else { |                 } else { | ||||||
|                         return Response::builder() |                     return Ok(Response::builder() | ||||||
|                         .status(StatusCode::UNPROCESSABLE_ENTITY) |                         .status(StatusCode::UNPROCESSABLE_ENTITY) | ||||||
|                         .body(NOTNUMERIC.into()) |                         .body(NOTNUMERIC.into()) | ||||||
|                             .unwrap(); |                         .unwrap()); | ||||||
|                 } |                 } | ||||||
|             } else { |             } else { | ||||||
|                     return Response::builder() |                 return Ok(Response::builder() | ||||||
|                     .status(StatusCode::UNPROCESSABLE_ENTITY) |                     .status(StatusCode::UNPROCESSABLE_ENTITY) | ||||||
|                     .body(MISSING.into()) |                     .body(MISSING.into()) | ||||||
|                         .unwrap(); |                     .unwrap()); | ||||||
|             }; |             }; | ||||||
|  |  | ||||||
|             // Render the response. This will often involve |             // Render the response. This will often involve | ||||||
| @@ -70,27 +69,33 @@ fn param_example(req: Request<Body>) -> Box<dyn Future<Item=Response<Body>, Erro | |||||||
|             // responses such as InternalServiceError may be |             // responses such as InternalServiceError may be | ||||||
|             // needed here, too. |             // needed here, too. | ||||||
|             let body = format!("Hello {}, your number is {}", name, number); |             let body = format!("Hello {}, your number is {}", name, number); | ||||||
|                 Response::new(body.into()) |             Ok(Response::new(body.into())) | ||||||
|             })) |  | ||||||
|         }, |         }, | ||||||
|         _ => { |         _ => { | ||||||
|             Box::new(future::ok(Response::builder() |             Ok(Response::builder() | ||||||
|                         .status(StatusCode::NOT_FOUND) |                         .status(StatusCode::NOT_FOUND) | ||||||
|                         .body(Body::empty()) |                         .body(Body::empty()) | ||||||
|                                 .unwrap())) |                         .unwrap()) | ||||||
|  |         } | ||||||
|     } |     } | ||||||
| } | } | ||||||
|  |  | ||||||
| } | #[hyper::rt::main] | ||||||
|  | async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> { | ||||||
| fn main() { |  | ||||||
|     pretty_env_logger::init(); |     pretty_env_logger::init(); | ||||||
|  |  | ||||||
|     let addr = ([127, 0, 0, 1], 1337).into(); |     let addr = ([127, 0, 0, 1], 1337).into(); | ||||||
|  |  | ||||||
|     let server = Server::bind(&addr) |     let server = Server::bind(&addr) | ||||||
|         .serve(|| service_fn(param_example)) |         .serve(make_service_fn(|_| { | ||||||
|         .map_err(|e| eprintln!("server error: {}", e)); |             async { | ||||||
|  |                 Ok::<_, hyper::Error>(service_fn(param_example)) | ||||||
|     hyper::rt::run(server); |             } | ||||||
|  |         })); | ||||||
|  |  | ||||||
|  |     println!("Listening on http://{}", addr); | ||||||
|  |  | ||||||
|  |     server.await?; | ||||||
|  |  | ||||||
|  |     Ok(()) | ||||||
| } | } | ||||||
|   | |||||||
		Reference in New Issue
	
	Block a user