docs(examples): add more comments to hello server example

This commit is contained in:
Sean McArthur
2019-08-30 14:38:22 -07:00
parent eee2a72879
commit 0331219b40

View File

@@ -1,9 +1,11 @@
#![deny(warnings)] #![deny(warnings)]
use std::convert::Infallible;
use hyper::{Body, Request, Response, Server}; use hyper::{Body, Request, Response, Server};
use hyper::service::{make_service_fn, service_fn}; use hyper::service::{make_service_fn, service_fn};
async fn hello(_: Request<Body>) -> Result<Response<Body>, hyper::Error> { async fn hello(_: Request<Body>) -> Result<Response<Body>, Infallible> {
Ok(Response::new(Body::from("Hello World!"))) Ok(Response::new(Body::from("Hello World!")))
} }
@@ -11,17 +13,20 @@ async fn hello(_: Request<Body>) -> Result<Response<Body>, hyper::Error> {
pub async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> { pub async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
pretty_env_logger::init(); pretty_env_logger::init();
let addr = ([127, 0, 0, 1], 3000).into(); // For every connection, we must make a `Service` to handle all
// incoming HTTP requests on said connection.
let server = Server::bind(&addr) let make_svc = make_service_fn(|_conn| {
.serve(make_service_fn(|_| {
// This is the `Service` that will handle the connection. // This is the `Service` that will handle the connection.
// `service_fn` is a helper to convert a function that // `service_fn` is a helper to convert a function that
// returns a Response into a `Service`. // returns a Response into a `Service`.
async { async {
Ok::<_, hyper::Error>(service_fn(hello)) Ok::<_, Infallible>(service_fn(hello))
} }
})); });
let addr = ([127, 0, 0, 1], 3000).into();
let server = Server::bind(&addr).serve(make_svc);
println!("Listening on http://{}", addr); println!("Listening on http://{}", addr);