From 6efc1a1cce0abdd4e3263e7ea328ad49616d8050 Mon Sep 17 00:00:00 2001 From: David Pedersen Date: Fri, 19 Feb 2021 22:50:43 +0100 Subject: [PATCH] docs(server): add server example using `tower::make::Shared` (#2440) `tower` 0.4.5 introduced `Shared` which is a `MakeService` that produces services by cloning an inner service. This works quite well with `hyper` if your service doesn't need the incoming connection and implements `Clone`. However that might not be entirely obvious so I thought it made sense to add an example to the docs. I wasn't quite sure if the example should go in the server or service module docs but since there already is an example using `make_service_fn` in the server docs I opted to add it there. Let me know if you'd rather have it somewhere else. --- Cargo.toml | 1 + src/server/mod.rs | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/Cargo.toml b/Cargo.toml index f63170bee4..6392b207cd 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -66,6 +66,7 @@ tokio = { version = "1", features = [ ] } tokio-test = "0.4" tokio-util = { version = "0.6", features = ["codec"] } +tower = { version = "0.4", features = ["make"] } tower-util = "0.3" url = "2.2" diff --git a/src/server/mod.rs b/src/server/mod.rs index a66cc0fcc2..7647449adf 100644 --- a/src/server/mod.rs +++ b/src/server/mod.rs @@ -50,6 +50,41 @@ //! # #[cfg(not(feature = "runtime"))] //! # fn main() {} //! ``` +//! +//! If you don't need the connection and your service implements `Clone` you can use +//! [`tower::make::Shared`] instead of `make_service_fn` which is a bit simpler: +//! +//! ```no_run +//! # use std::convert::Infallible; +//! # use std::net::SocketAddr; +//! # use hyper::{Body, Request, Response, Server}; +//! # use hyper::service::{make_service_fn, service_fn}; +//! # use tower::make::Shared; +//! # async fn handle(_req: Request) -> Result, Infallible> { +//! # Ok(Response::new(Body::from("Hello World"))) +//! # } +//! # #[cfg(feature = "runtime")] +//! #[tokio::main] +//! async fn main() { +//! // Construct our SocketAddr to listen on... +//! let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); +//! +//! // Shared is a MakeService that produces services by cloning an inner service... +//! let make_service = Shared::new(service_fn(handle)); +//! +//! // Then bind and serve... +//! let server = Server::bind(&addr).serve(make_service); +//! +//! // And run forever... +//! if let Err(e) = server.await { +//! eprintln!("server error: {}", e); +//! } +//! } +//! # #[cfg(not(feature = "runtime"))] +//! # fn main() {} +//! ``` +//! +//! [`tower::make::Shared`]: https://docs.rs/tower/latest/tower/make/struct.Shared.html pub mod accept;