Skip to content

Commit 6efc1a1

Browse files
authored
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.
1 parent f01de8e commit 6efc1a1

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,7 @@ tokio = { version = "1", features = [
6666
] }
6767
tokio-test = "0.4"
6868
tokio-util = { version = "0.6", features = ["codec"] }
69+
tower = { version = "0.4", features = ["make"] }
6970
tower-util = "0.3"
7071
url = "2.2"
7172

src/server/mod.rs

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,41 @@
5050
//! # #[cfg(not(feature = "runtime"))]
5151
//! # fn main() {}
5252
//! ```
53+
//!
54+
//! If you don't need the connection and your service implements `Clone` you can use
55+
//! [`tower::make::Shared`] instead of `make_service_fn` which is a bit simpler:
56+
//!
57+
//! ```no_run
58+
//! # use std::convert::Infallible;
59+
//! # use std::net::SocketAddr;
60+
//! # use hyper::{Body, Request, Response, Server};
61+
//! # use hyper::service::{make_service_fn, service_fn};
62+
//! # use tower::make::Shared;
63+
//! # async fn handle(_req: Request<Body>) -> Result<Response<Body>, Infallible> {
64+
//! # Ok(Response::new(Body::from("Hello World")))
65+
//! # }
66+
//! # #[cfg(feature = "runtime")]
67+
//! #[tokio::main]
68+
//! async fn main() {
69+
//! // Construct our SocketAddr to listen on...
70+
//! let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
71+
//!
72+
//! // Shared is a MakeService that produces services by cloning an inner service...
73+
//! let make_service = Shared::new(service_fn(handle));
74+
//!
75+
//! // Then bind and serve...
76+
//! let server = Server::bind(&addr).serve(make_service);
77+
//!
78+
//! // And run forever...
79+
//! if let Err(e) = server.await {
80+
//! eprintln!("server error: {}", e);
81+
//! }
82+
//! }
83+
//! # #[cfg(not(feature = "runtime"))]
84+
//! # fn main() {}
85+
//! ```
86+
//!
87+
//! [`tower::make::Shared`]: https://docs.rs/tower/latest/tower/make/struct.Shared.html
5388
5489
pub mod accept;
5590

0 commit comments

Comments
 (0)