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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
use crate::router::{RouteTarget, Router};
use crate::static_files::StaticFiles;
use crate::state::State;
use crate::ws::WebSocket;
use crate::endpoint::Endpoint;
use crate::{Responder, Request, Result, Response};
use crate::filter::{Filter, Next};
use hyper::server::conn::AddrStream;
use hyper::service::{make_service_fn, service_fn};
use hyper::{Body, Method};
use log::info;
use std::convert::Infallible;
use std::future::Future;
use std::path::PathBuf;
use std::sync::Arc;
use tokio::net::ToSocketAddrs;
use async_trait::async_trait;
pub struct App<S: State> {
state: S,
routes: Router<S>,
filters: Vec<Box<dyn Filter<S> + Send + Sync + 'static>>,
}
pub struct Route<'a, 'p, S: State>
{
path: &'p str,
app: &'a mut App<S>,
}
impl<'a, 'p, S: State> Route<'a, 'p, S>
{
pub fn method(self, method: Method, ep: impl Endpoint<S> + Send + Sync + 'static) -> Self {
self.app.routes.add(method, self.path, ep);
self
}
pub fn all(self, ep: impl Endpoint<S> + Send + Sync + 'static) -> Self {
self.app.routes.add_all(self.path, ep);
self
}
pub fn get(self, ep: impl Endpoint<S> + Send + Sync + 'static) -> Self {
self.method(Method::GET, ep)
}
pub fn post(self, ep: impl Endpoint<S> + Send + Sync + 'static) -> Self {
self.method(Method::POST, ep)
}
pub fn put(self, ep: impl Endpoint<S> + Send + Sync + 'static) -> Self {
self.method(Method::PUT, ep)
}
pub fn delete(self, ep: impl Endpoint<S> + Send + Sync + 'static) -> Self {
self.method(Method::DELETE, ep)
}
pub fn static_files(self, root: impl Into<PathBuf>) -> Self {
let prefix = self.path.to_owned();
self.method(Method::GET, StaticFiles::new(root, prefix))
}
pub fn mount(&mut self, app: App<S>)
{
let path = self.path.to_owned() + "/*-highnoon-path-rest-";
let route = Route { app: self.app, path: &path };
route.all(app);
}
pub fn ws<H, F>(self, handler: H)
where
H: Send + Sync + 'static + Fn(WebSocket) -> F,
F: Future<Output = Result<()>> + Send + 'static,
{
self.method(Method::GET, crate::ws::endpoint(handler));
}
}
impl<S: State> App<S>
{
pub fn new(state: S) -> Self {
Self {
state,
routes: Router::new(),
filters: vec![],
}
}
pub fn state(&self) -> &S {
&self.state
}
pub fn with<F>(&mut self, filter: F)
where
F: Filter<S> + Send + Sync + 'static
{
self.filters.push(Box::new(filter));
}
pub fn at<'a, 'p>(&'a mut self, path: &'p str) -> Route<'a, 'p, S> {
Route { path, app: self }
}
pub async fn listen(self, host: impl ToSocketAddrs) -> anyhow::Result<()> {
let app = Arc::new(self);
let mut addrs = tokio::net::lookup_host(host).await?;
let addr = addrs
.next()
.ok_or_else(|| anyhow::Error::msg("host lookup returned no hosts"))?;
let server = hyper::Server::bind(&addr);
let make_svc = make_service_fn(|addr_stream: &AddrStream| {
let app = Arc::clone(&app);
let addr = addr_stream.remote_addr();
async move {
Ok::<_, Infallible>(service_fn(move |req: hyper::Request<Body>| {
let app = Arc::clone(&app);
async move {
let RouteTarget { ep, params } =
app.routes.lookup(req.method(), req.uri().path());
let req = Request::new(Arc::clone(&app), req, params, addr);
let next = Next { ep, rest: &*app.filters };
next.next(req)
.await
.or_else(|err| err.into_response())
.map(|resp| resp.into_inner())
.map_err(|err| err.into_std())
}
}))
}
});
info!("server listening on {}", addr);
server.serve(make_svc).await?;
Ok(())
}
}
#[async_trait]
impl<S: State> Endpoint<S> for App<S>
{
async fn call(&self, mut req: Request<S>) -> Result<Response> {
let path_rest = req.param("-highnoon-path-rest-")?;
let RouteTarget { ep, params } =
self.routes.lookup(req.method(), path_rest);
req.merge_params(params);
let next = Next { ep, rest: &*self.filters };
next.next(req).await
}
}