|
16 | 16 | //!
|
17 | 17 | //! [`Server`](Server) accepts connections in both HTTP1 and HTTP2 by default.
|
18 | 18 | //!
|
19 |
| -//! ## Example |
| 19 | +//! ## Examples |
20 | 20 | //!
|
21 | 21 | //! ```no_run
|
22 | 22 | //! use std::convert::Infallible;
|
|
84 | 84 | //! # fn main() {}
|
85 | 85 | //! ```
|
86 | 86 | //!
|
| 87 | +//! Passing data to your request handler can be done like so: |
| 88 | +//! |
| 89 | +//! ```no_run |
| 90 | +//! use std::convert::Infallible; |
| 91 | +//! use std::net::SocketAddr; |
| 92 | +//! use hyper::{Body, Request, Response, Server}; |
| 93 | +//! use hyper::service::{make_service_fn, service_fn}; |
| 94 | +//! use hyper::server::conn::AddrStream; |
| 95 | +//! |
| 96 | +//! #[derive(Clone)] |
| 97 | +//! struct AppContext { |
| 98 | +//! // Whatever data your application needs can go here |
| 99 | +//! } |
| 100 | +//! |
| 101 | +//! async fn handle( |
| 102 | +//! context: AppContext, |
| 103 | +//! addr: SocketAddr, |
| 104 | +//! req: Request<Body> |
| 105 | +//! ) -> Result<Response<Body>, Infallible> { |
| 106 | +//! Ok(Response::new(Body::from("Hello World"))) |
| 107 | +//! } |
| 108 | +//! |
| 109 | +//! # #[cfg(feature = "runtime")] |
| 110 | +//! #[tokio::main] |
| 111 | +//! async fn main() { |
| 112 | +//! let context = AppContext { |
| 113 | +//! // ... |
| 114 | +//! }; |
| 115 | +//! |
| 116 | +//! // A `MakeService` that produces a `Service` to handle each connection. |
| 117 | +//! let make_service = make_service_fn(move |conn: &AddrStream| { |
| 118 | +//! // We have to clone the context to share it with each invocation of |
| 119 | +//! // `make_service`. If your data doesn't implement `Clone` consider using |
| 120 | +//! // an `std::sync::Arc`. |
| 121 | +//! let context = context.clone(); |
| 122 | +//! |
| 123 | +//! // You can grab the address of the incoming connection like so. |
| 124 | +//! let addr = conn.remote_addr(); |
| 125 | +//! |
| 126 | +//! // Create a `Service` for responding to the request. |
| 127 | +//! let service = service_fn(move |req| { |
| 128 | +//! handle(context.clone(), addr, req) |
| 129 | +//! }); |
| 130 | +//! |
| 131 | +//! // Return the service to hyper. |
| 132 | +//! async move { Ok::<_, Infallible>(service) } |
| 133 | +//! }); |
| 134 | +//! |
| 135 | +//! // Run the server like above... |
| 136 | +//! let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); |
| 137 | +//! |
| 138 | +//! let server = Server::bind(&addr).serve(make_service); |
| 139 | +//! |
| 140 | +//! if let Err(e) = server.await { |
| 141 | +//! eprintln!("server error: {}", e); |
| 142 | +//! } |
| 143 | +//! } |
| 144 | +//! # #[cfg(not(feature = "runtime"))] |
| 145 | +//! # fn main() {} |
| 146 | +//! ``` |
| 147 | +//! |
87 | 148 | //! [`tower::make::Shared`]: https://docs.rs/tower/latest/tower/make/struct.Shared.html
|
88 | 149 |
|
89 | 150 | pub mod accept;
|
|
0 commit comments