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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
use routefinder::{Match, Router as Routefinder};
use std::{collections::HashMap, sync::Arc};
use trillium::{async_trait, http_types::Method, Conn, Handler, Upgrade};
use crate::RouterRef;
#[derive(Default, Debug)]
pub struct Router(HashMap<Method, Routefinder<Box<dyn Handler>>>);
macro_rules! method {
($fn_name:ident, $method:ident) => {
method!(
$fn_name,
$method,
concat!(
"Registers a handler for the ",
stringify!($fn_name),
" http method.
```
# use trillium::Conn;
# use trillium_router::Router;
let router = Router::new().",
stringify!($fn_name),
"(\"/some/route\", |conn: Conn| async move {
conn.ok(\"success\")
});
use trillium_testing::{methods::",
stringify!($fn_name),
", assert_ok, assert_not_handled};
assert_ok!(",
stringify!($fn_name),
"(\"/some/route\").on(&router), \"success\");
assert_not_handled!(",
stringify!($fn_name),
"(\"/other/route\").on(&router));
```
"
)
);
};
($fn_name:ident, $method:ident, $doc_comment:expr) => {
#[doc = $doc_comment]
pub fn $fn_name(mut self, path: &'static str, handler: impl Handler) -> Self {
self.add(path, Method::$method, handler);
self
}
};
}
impl Router {
pub fn new() -> Self {
Self::default()
}
pub fn build(builder: impl Fn(RouterRef)) -> Router {
let mut router = Router::new();
builder(RouterRef::new(&mut router));
router
}
fn best_match<'a, 'b>(
&'a self,
method: &Method,
path: &'b str,
) -> Option<Match<'a, 'b, Box<dyn Handler>>> {
self.0.get(method).and_then(|r| r.best_match(path))
}
pub(crate) fn add(&mut self, path: &'static str, method: Method, handler: impl Handler) {
self.0
.entry(method)
.or_insert_with(routefinder::Router::new)
.add(path, Box::new(handler))
.expect("could not add route")
}
pub(crate) fn add_any(&mut self, path: &'static str, handler: impl Handler) {
use Method::*;
let handler = Arc::new(handler);
for method in &[Get, Post, Put, Delete, Patch] {
self.add(path, *method, handler.clone())
}
}
pub fn any(mut self, path: &'static str, handler: impl Handler) -> Self {
self.add_any(path, handler);
self
}
method!(get, Get);
method!(post, Post);
method!(put, Put);
method!(delete, Delete);
method!(patch, Patch);
}
#[async_trait]
impl Handler for Router {
async fn run(&self, conn: Conn) -> Conn {
if let Some(m) = self.best_match(&conn.method(), conn.path()) {
let captures = m.captures().into_owned();
struct HasPath;
log::debug!("running {}: {}", m.route(), m.name());
let mut new_conn = m
.handler()
.run({
let mut conn = conn;
if let Some(wildcard) = captures.wildcard() {
conn.push_path(String::from(wildcard));
conn.set_state(HasPath);
}
conn.with_state(captures)
})
.await;
if new_conn.take_state::<HasPath>().is_some() {
new_conn.pop_path();
}
new_conn
} else {
log::debug!("{} did not match any route", conn.path());
conn
}
}
async fn before_send(&self, conn: Conn) -> Conn {
if let Some(m) = self.best_match(&conn.method(), conn.path()) {
m.handler().before_send(conn).await
} else {
conn
}
}
fn has_upgrade(&self, upgrade: &Upgrade) -> bool {
if let Some(m) = self.best_match(&upgrade.method(), upgrade.path()) {
m.handler().has_upgrade(upgrade)
} else {
false
}
}
async fn upgrade(&self, upgrade: Upgrade) {
self.best_match(&upgrade.method(), upgrade.path())
.unwrap()
.handler()
.upgrade(upgrade)
.await
}
}