logo
  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
use std::{mem, rc::Rc};

use actix_http::Method;
use actix_service::{
    boxed::{self, BoxService},
    fn_service, Service, ServiceFactory, ServiceFactoryExt,
};
use futures_core::future::LocalBoxFuture;

use crate::{
    guard::{self, Guard},
    handler::{handler_service, Handler},
    service::{BoxedHttpServiceFactory, ServiceRequest, ServiceResponse},
    Error, FromRequest, HttpResponse, Responder,
};

/// A request handler with [guards](guard).
///
/// Route uses a builder-like pattern for configuration. If handler is not set, a `404 Not Found`
/// handler is used.
pub struct Route {
    service: BoxedHttpServiceFactory,
    guards: Rc<Vec<Box<dyn Guard>>>,
}

impl Route {
    /// Create new route which matches any request.
    #[allow(clippy::new_without_default)]
    pub fn new() -> Route {
        Route {
            service: boxed::factory(fn_service(|req: ServiceRequest| async {
                Ok(req.into_response(HttpResponse::NotFound()))
            })),
            guards: Rc::new(Vec::new()),
        }
    }

    pub(crate) fn take_guards(&mut self) -> Vec<Box<dyn Guard>> {
        mem::take(Rc::get_mut(&mut self.guards).unwrap())
    }
}

impl ServiceFactory<ServiceRequest> for Route {
    type Response = ServiceResponse;
    type Error = Error;
    type Config = ();
    type Service = RouteService;
    type InitError = ();
    type Future = LocalBoxFuture<'static, Result<Self::Service, Self::InitError>>;

    fn new_service(&self, _: ()) -> Self::Future {
        let fut = self.service.new_service(());
        let guards = self.guards.clone();

        Box::pin(async move {
            let service = fut.await?;
            Ok(RouteService { service, guards })
        })
    }
}

pub struct RouteService {
    service: BoxService<ServiceRequest, ServiceResponse, Error>,
    guards: Rc<Vec<Box<dyn Guard>>>,
}

impl RouteService {
    // TODO: does this need to take &mut ?
    pub fn check(&self, req: &mut ServiceRequest) -> bool {
        let guard_ctx = req.guard_ctx();

        for guard in self.guards.iter() {
            if !guard.check(&guard_ctx) {
                return false;
            }
        }
        true
    }
}

impl Service<ServiceRequest> for RouteService {
    type Response = ServiceResponse;
    type Error = Error;
    type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;

    actix_service::forward_ready!(service);

    fn call(&self, req: ServiceRequest) -> Self::Future {
        self.service.call(req)
    }
}

impl Route {
    /// Add method guard to the route.
    ///
    /// # Examples
    /// ```
    /// # 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.
    ///
    /// # Examples
    /// ```
    /// # 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.
    ///
    /// # Examples
    /// ```
    /// use actix_web::{web, http, App};
    /// use serde::Deserialize;
    ///
    /// #[derive(Deserialize)]
    /// struct Info {
    ///     username: String,
    /// }
    ///
    /// /// extract path info using serde
    /// async fn index(info: web::Path<Info>) -> String {
    ///     format!("Welcome {}!", info.username)
    /// }
    ///
    /// 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.
    /// ```
    /// # use std::collections::HashMap;
    /// # use serde::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)
    /// }
    ///
    /// let app = App::new().service(
    ///     web::resource("/{username}/index.html") // <- define path parameters
    ///         .route(web::get().to(index))
    /// );
    /// ```
    pub fn to<F, Args>(mut self, handler: F) -> Self
    where
        F: Handler<Args>,
        Args: FromRequest + 'static,
        F::Output: Responder + 'static,
    {
        self.service = handler_service(handler);
        self
    }

    /// Set raw service to be constructed and called as the request handler.
    ///
    /// # Examples
    /// ```
    /// # use std::convert::Infallible;
    /// # use futures_util::future::LocalBoxFuture;
    /// # use actix_web::{*, dev::*, http::header};
    /// struct HelloWorld;
    ///
    /// impl Service<ServiceRequest> for HelloWorld {
    ///     type Response = ServiceResponse;
    ///     type Error = Infallible;
    ///     type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;
    ///
    ///     dev::always_ready!();
    ///
    ///     fn call(&self, req: ServiceRequest) -> Self::Future {
    ///         let (req, _) = req.into_parts();
    ///
    ///         let res = HttpResponse::Ok()
    ///             .insert_header(header::ContentType::plaintext())
    ///             .body("Hello world!");
    ///
    ///         Box::pin(async move { Ok(ServiceResponse::new(req, res)) })
    ///     }
    /// }
    ///
    /// App::new().route(
    ///     "/",
    ///     web::get().service(fn_factory(|| async { Ok(HelloWorld) })),
    /// );
    /// ```
    pub fn service<S, E>(mut self, service_factory: S) -> Self
    where
        S: ServiceFactory<
                ServiceRequest,
                Response = ServiceResponse,
                Error = E,
                InitError = (),
                Config = (),
            > + 'static,
        E: Into<Error> + 'static,
    {
        self.service = boxed::factory(service_factory.map_err(Into::into));
        self
    }
}

#[cfg(test)]
mod tests {
    use std::{convert::Infallible, time::Duration};

    use actix_rt::time::sleep;
    use bytes::Bytes;
    use futures_core::future::LocalBoxFuture;
    use serde::Serialize;

    use crate::dev::{always_ready, fn_factory, fn_service, Service};
    use crate::http::{header, Method, StatusCode};
    use crate::service::{ServiceRequest, ServiceResponse};
    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 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 {
                            sleep(Duration::from_millis(100)).await;
                            Ok::<_, Infallible>(HttpResponse::Created())
                        }))
                        .route(web::delete().to(|| async {
                            sleep(Duration::from_millis(100)).await;
                            Err::<HttpResponse, _>(error::ErrorBadRequest("err"))
                        })),
                )
                .service(web::resource("/json").route(web::get().to(|| async {
                    sleep(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(&srv, req).await;
        assert_eq!(resp.status(), StatusCode::OK);

        let req = TestRequest::with_uri("/test")
            .method(Method::POST)
            .to_request();
        let resp = call_service(&srv, req).await;
        assert_eq!(resp.status(), StatusCode::CREATED);

        let req = TestRequest::with_uri("/test")
            .method(Method::PUT)
            .to_request();
        let resp = call_service(&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(&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(&srv, req).await;
        assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED);

        let req = TestRequest::with_uri("/json").to_request();
        let resp = call_service(&srv, req).await;
        assert_eq!(resp.status(), StatusCode::OK);

        let body = read_body(resp).await;
        assert_eq!(body, Bytes::from_static(b"{\"name\":\"test\"}"));
    }

    #[actix_rt::test]
    async fn test_service_handler() {
        struct HelloWorld;

        impl Service<ServiceRequest> for HelloWorld {
            type Response = ServiceResponse;
            type Error = crate::Error;
            type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;

            always_ready!();

            fn call(&self, req: ServiceRequest) -> Self::Future {
                let (req, _) = req.into_parts();

                let res = HttpResponse::Ok()
                    .insert_header(header::ContentType::plaintext())
                    .body("Hello world!");

                Box::pin(async move { Ok(ServiceResponse::new(req, res)) })
            }
        }

        let srv = init_service(
            App::new()
                .route(
                    "/hello",
                    web::get().service(fn_factory(|| async { Ok(HelloWorld) })),
                )
                .route(
                    "/bye",
                    web::get().service(fn_factory(|| async {
                        Ok::<_, ()>(fn_service(|req: ServiceRequest| async {
                            let (req, _) = req.into_parts();

                            let res = HttpResponse::Ok()
                                .insert_header(header::ContentType::plaintext())
                                .body("Goodbye, and thanks for all the fish!");

                            Ok::<_, Infallible>(ServiceResponse::new(req, res))
                        }))
                    })),
                ),
        )
        .await;

        let req = TestRequest::get().uri("/hello").to_request();
        let resp = call_service(&srv, req).await;
        assert_eq!(resp.status(), StatusCode::OK);
        let body = read_body(resp).await;
        assert_eq!(body, Bytes::from_static(b"Hello world!"));

        let req = TestRequest::get().uri("/bye").to_request();
        let resp = call_service(&srv, req).await;
        assert_eq!(resp.status(), StatusCode::OK);
        let body = read_body(resp).await;
        assert_eq!(
            body,
            Bytes::from_static(b"Goodbye, and thanks for all the fish!")
        );
    }
}