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.
This commit is contained in:
@@ -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"
|
||||
|
||||
|
||||
@@ -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;
|
||||
|
||||
|
||||
Reference in New Issue
Block a user