Skip to content

Commit

Permalink
docs(server): add server example using tower::make::Shared (#2440)
Browse files Browse the repository at this point in the history
`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.
  • Loading branch information
davidpdrsn committed Feb 19, 2021
1 parent f01de8e commit 6efc1a1
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 0 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Expand Up @@ -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"

Expand Down
35 changes: 35 additions & 0 deletions src/server/mod.rs
Expand Up @@ -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<Body>) -> Result<Response<Body>, 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;

Expand Down

0 comments on commit 6efc1a1

Please sign in to comment.