1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
use crateRouter;
use crate;
use Service;
use Infallible;
use ;
use TcpStream;
/// A [`Service`](https://docs.rs/hyper/0.14.4/hyper/service/trait.Service.html) to process incoming requests.
///
/// This `RouterService<B, E>` type accepts two type parameters: `B` and `E`.
///
/// * The `B` represents the response body type which will be used by route handlers and the middlewares and this body type must implement
/// the [HttpBody](https://docs.rs/hyper/0.14.4/hyper/body/trait.HttpBody.html) trait. For an instance, `B` could be [hyper::Body](https://docs.rs/hyper/0.14.4/hyper/body/struct.Body.html)
/// type.
/// * The `E` represents any error type which will be used by route handlers and the middlewares. This error type must implement the [std::error::Error](https://doc.rust-lang.org/std/error/trait.Error.html).
///
/// # Examples
///
/// ```no_run
/// use http_body_util::Full;
/// use hyper::body::Bytes;
/// use hyper::service::Service;
/// use hyper::{Request, Response};
/// use hyper_util::rt::TokioExecutor;
/// use hyper_util::rt::TokioIo;
/// use hyper_util::server::conn::auto::Builder;
/// use routerify_ng::{Router, RouterService};
/// use std::convert::Infallible;
/// use std::net::SocketAddr;
/// use std::sync::Arc;
/// use tokio::net::TcpListener;
///
/// async fn home(_: Request<Full<Bytes>>) -> Result<Response<Full<Bytes>>, Infallible> {
/// Ok(Response::new(Full::new(Bytes::from("Home page"))))
/// }
///
/// fn router() -> Router<Infallible> {
/// Router::builder().get("/", home).build().unwrap()
/// }
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
/// let router = router();
///
/// // Create a Service from the router above to handle incoming requests.
/// let service = Arc::new(RouterService::new(router).unwrap());
///
/// let addr: SocketAddr = SocketAddr::from(([127, 0, 0, 1], 3001));
///
/// // Create a server by binding to the address.
/// let listener = TcpListener::bind(addr).await?;
/// println!("App is running on: {}", addr);
///
/// loop {
/// let (stream, _) = listener.accept().await?;
///
/// let router_service = service.clone();
///
/// tokio::spawn(async move {
/// // Get the request service for this connection
/// let request_service = router_service.call(&stream).await.unwrap();
///
/// // Wrap the stream in TokioIo for hyper
/// let io = TokioIo::new(stream);
///
/// // Serve the connection
/// let builder = Builder::new(TokioExecutor::new());
/// if let Err(err) = builder.serve_connection(io, request_service).await {
/// eprintln!("Error serving connection: {:?}", err);
/// }
/// });
/// }
/// }
/// ```