forked from actix/actix-web
-
Notifications
You must be signed in to change notification settings - Fork 0
/
route.rs
431 lines (388 loc) · 12.5 KB
/
route.rs
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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
use std::future::Future;
use std::pin::Pin;
use std::rc::Rc;
use std::task::{Context, Poll};
use actix_http::{http::Method, Error};
use actix_service::{Service, ServiceFactory};
use futures::future::{ready, FutureExt, LocalBoxFuture};
use crate::extract::FromRequest;
use crate::guard::{self, Guard};
use crate::handler::{Extract, Factory, Handler};
use crate::responder::Responder;
use crate::service::{ServiceRequest, ServiceResponse};
use crate::HttpResponse;
type BoxedRouteService<Req, Res> = Box<
dyn Service<
Request = Req,
Response = Res,
Error = Error,
Future = LocalBoxFuture<'static, Result<Res, Error>>,
>,
>;
type BoxedRouteNewService<Req, Res> = Box<
dyn ServiceFactory<
Config = (),
Request = Req,
Response = Res,
Error = Error,
InitError = (),
Service = BoxedRouteService<Req, Res>,
Future = LocalBoxFuture<'static, Result<BoxedRouteService<Req, Res>, ()>>,
>,
>;
/// Resource route definition
///
/// Route uses builder-like pattern for configuration.
/// If handler is not explicitly set, default *404 Not Found* handler is used.
pub struct Route {
service: BoxedRouteNewService<ServiceRequest, ServiceResponse>,
guards: Rc<Vec<Box<dyn Guard>>>,
}
impl Route {
/// Create new route which matches any request.
pub fn new() -> Route {
Route {
service: Box::new(RouteNewService::new(Extract::new(Handler::new(|| {
ready(HttpResponse::NotFound())
})))),
guards: Rc::new(Vec::new()),
}
}
pub(crate) fn take_guards(&mut self) -> Vec<Box<dyn Guard>> {
std::mem::replace(Rc::get_mut(&mut self.guards).unwrap(), Vec::new())
}
}
impl ServiceFactory for Route {
type Config = ();
type Request = ServiceRequest;
type Response = ServiceResponse;
type Error = Error;
type InitError = ();
type Service = RouteService;
type Future = CreateRouteService;
fn new_service(&self, _: ()) -> Self::Future {
CreateRouteService {
fut: self.service.new_service(()),
guards: self.guards.clone(),
}
}
}
type RouteFuture = LocalBoxFuture<
'static,
Result<BoxedRouteService<ServiceRequest, ServiceResponse>, ()>,
>;
#[pin_project::pin_project]
pub struct CreateRouteService {
#[pin]
fut: RouteFuture,
guards: Rc<Vec<Box<dyn Guard>>>,
}
impl Future for CreateRouteService {
type Output = Result<RouteService, ()>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.project();
match this.fut.poll(cx)? {
Poll::Ready(service) => Poll::Ready(Ok(RouteService {
service,
guards: this.guards.clone(),
})),
Poll::Pending => Poll::Pending,
}
}
}
pub struct RouteService {
service: BoxedRouteService<ServiceRequest, ServiceResponse>,
guards: Rc<Vec<Box<dyn Guard>>>,
}
impl RouteService {
pub fn check(&self, req: &mut ServiceRequest) -> bool {
for f in self.guards.iter() {
if !f.check(req.head()) {
return false;
}
}
true
}
}
impl Service for RouteService {
type Request = ServiceRequest;
type Response = ServiceResponse;
type Error = Error;
type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.service.poll_ready(cx)
}
fn call(&mut self, req: ServiceRequest) -> Self::Future {
self.service.call(req).boxed_local()
}
}
impl Route {
/// Add method guard to the route.
///
/// ```rust
/// # use actix_web::*;
/// # fn main() {
/// App::new().service(web::resource("/path").route(
/// web::get()
/// .method(http::Method::CONNECT)
/// .guard(guard::Header("content-type", "text/plain"))
/// .to(|req: HttpRequest| HttpResponse::Ok()))
/// );
/// # }
/// ```
pub fn method(mut self, method: Method) -> Self {
Rc::get_mut(&mut self.guards)
.unwrap()
.push(Box::new(guard::Method(method)));
self
}
/// Add guard to the route.
///
/// ```rust
/// # use actix_web::*;
/// # fn main() {
/// App::new().service(web::resource("/path").route(
/// web::route()
/// .guard(guard::Get())
/// .guard(guard::Header("content-type", "text/plain"))
/// .to(|req: HttpRequest| HttpResponse::Ok()))
/// );
/// # }
/// ```
pub fn guard<F: Guard + 'static>(mut self, f: F) -> Self {
Rc::get_mut(&mut self.guards).unwrap().push(Box::new(f));
self
}
/// Set handler function, use request extractors for parameters.
///
/// ```rust
/// use actix_web::{web, http, App};
/// use serde_derive::Deserialize;
///
/// #[derive(Deserialize)]
/// struct Info {
/// username: String,
/// }
///
/// /// extract path info using serde
/// async fn index(info: web::Path<Info>) -> String {
/// format!("Welcome {}!", info.username)
/// }
///
/// fn main() {
/// let app = App::new().service(
/// web::resource("/{username}/index.html") // <- define path parameters
/// .route(web::get().to(index)) // <- register handler
/// );
/// }
/// ```
///
/// It is possible to use multiple extractors for one handler function.
///
/// ```rust
/// # use std::collections::HashMap;
/// # use serde_derive::Deserialize;
/// use actix_web::{web, App};
///
/// #[derive(Deserialize)]
/// struct Info {
/// username: String,
/// }
///
/// /// extract path info using serde
/// async fn index(path: web::Path<Info>, query: web::Query<HashMap<String, String>>, body: web::Json<Info>) -> String {
/// format!("Welcome {}!", path.username)
/// }
///
/// fn main() {
/// let app = App::new().service(
/// web::resource("/{username}/index.html") // <- define path parameters
/// .route(web::get().to(index))
/// );
/// }
/// ```
pub fn to<F, T, R, U>(mut self, handler: F) -> Self
where
F: Factory<T, R, U>,
T: FromRequest + 'static,
R: Future<Output = U> + 'static,
U: Responder + 'static,
{
self.service =
Box::new(RouteNewService::new(Extract::new(Handler::new(handler))));
self
}
}
struct RouteNewService<T>
where
T: ServiceFactory<Request = ServiceRequest, Error = (Error, ServiceRequest)>,
{
service: T,
}
impl<T> RouteNewService<T>
where
T: ServiceFactory<
Config = (),
Request = ServiceRequest,
Response = ServiceResponse,
Error = (Error, ServiceRequest),
>,
T::Future: 'static,
T::Service: 'static,
<T::Service as Service>::Future: 'static,
{
pub fn new(service: T) -> Self {
RouteNewService { service }
}
}
impl<T> ServiceFactory for RouteNewService<T>
where
T: ServiceFactory<
Config = (),
Request = ServiceRequest,
Response = ServiceResponse,
Error = (Error, ServiceRequest),
>,
T::Future: 'static,
T::Service: 'static,
<T::Service as Service>::Future: 'static,
{
type Config = ();
type Request = ServiceRequest;
type Response = ServiceResponse;
type Error = Error;
type InitError = ();
type Service = BoxedRouteService<ServiceRequest, Self::Response>;
type Future = LocalBoxFuture<'static, Result<Self::Service, Self::InitError>>;
fn new_service(&self, _: ()) -> Self::Future {
self.service
.new_service(())
.map(|result| match result {
Ok(service) => {
let service: BoxedRouteService<_, _> =
Box::new(RouteServiceWrapper { service });
Ok(service)
}
Err(_) => Err(()),
})
.boxed_local()
}
}
struct RouteServiceWrapper<T: Service> {
service: T,
}
impl<T> Service for RouteServiceWrapper<T>
where
T::Future: 'static,
T: Service<
Request = ServiceRequest,
Response = ServiceResponse,
Error = (Error, ServiceRequest),
>,
{
type Request = ServiceRequest;
type Response = ServiceResponse;
type Error = Error;
type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.service.poll_ready(cx).map_err(|(e, _)| e)
}
fn call(&mut self, req: ServiceRequest) -> Self::Future {
// let mut fut = self.service.call(req);
self.service
.call(req)
.map(|res| match res {
Ok(res) => Ok(res),
Err((err, req)) => Ok(req.error_response(err)),
})
.boxed_local()
// match fut.poll() {
// Poll::Ready(Ok(res)) => Either::Left(ok(res)),
// Poll::Ready(Err((e, req))) => Either::Left(ok(req.error_response(e))),
// Poll::Pending => Either::Right(Box::new(fut.then(|res| match res {
// Ok(res) => Ok(res),
// Err((err, req)) => Ok(req.error_response(err)),
// }))),
// }
}
}
#[cfg(test)]
mod tests {
use std::time::Duration;
use actix_rt::time::delay_for;
use bytes::Bytes;
use serde_derive::Serialize;
use crate::http::{Method, StatusCode};
use crate::test::{call_service, init_service, read_body, TestRequest};
use crate::{error, web, App, HttpResponse};
#[derive(Serialize, PartialEq, Debug)]
struct MyObject {
name: String,
}
#[actix_rt::test]
async fn test_route() {
let mut srv = init_service(
App::new()
.service(
web::resource("/test")
.route(web::get().to(|| HttpResponse::Ok()))
.route(web::put().to(|| {
async {
Err::<HttpResponse, _>(error::ErrorBadRequest("err"))
}
}))
.route(web::post().to(|| {
async {
delay_for(Duration::from_millis(100)).await;
HttpResponse::Created()
}
}))
.route(web::delete().to(|| {
async {
delay_for(Duration::from_millis(100)).await;
Err::<HttpResponse, _>(error::ErrorBadRequest("err"))
}
})),
)
.service(web::resource("/json").route(web::get().to(|| {
async {
delay_for(Duration::from_millis(25)).await;
web::Json(MyObject {
name: "test".to_string(),
})
}
}))),
)
.await;
let req = TestRequest::with_uri("/test")
.method(Method::GET)
.to_request();
let resp = call_service(&mut srv, req).await;
assert_eq!(resp.status(), StatusCode::OK);
let req = TestRequest::with_uri("/test")
.method(Method::POST)
.to_request();
let resp = call_service(&mut srv, req).await;
assert_eq!(resp.status(), StatusCode::CREATED);
let req = TestRequest::with_uri("/test")
.method(Method::PUT)
.to_request();
let resp = call_service(&mut srv, req).await;
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
let req = TestRequest::with_uri("/test")
.method(Method::DELETE)
.to_request();
let resp = call_service(&mut srv, req).await;
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
let req = TestRequest::with_uri("/test")
.method(Method::HEAD)
.to_request();
let resp = call_service(&mut srv, req).await;
assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED);
let req = TestRequest::with_uri("/json").to_request();
let resp = call_service(&mut srv, req).await;
assert_eq!(resp.status(), StatusCode::OK);
let body = read_body(resp).await;
assert_eq!(body, Bytes::from_static(b"{\"name\":\"test\"}"));
}
}