1
0
Fork 0
mirror of https://github.com/actix/actix-web.git synced 2024-12-18 14:16:47 +00:00
actix-web/src/route.rs

384 lines
12 KiB
Rust
Raw Normal View History

2020-10-10 00:26:05 +00:00
#![allow(clippy::rc_buffer)] // inner value is mutated before being shared (`Rc::get_mut`)
2021-02-27 21:00:36 +00:00
use std::{future::Future, rc::Rc};
2017-12-05 00:09:22 +00:00
2021-06-17 16:57:58 +00:00
use actix_http::http::Method;
2021-02-27 21:00:36 +00:00
use actix_service::{
boxed::{self, BoxService, BoxServiceFactory},
Service, ServiceFactory, ServiceFactoryExt,
2021-02-27 21:00:36 +00:00
};
use futures_core::future::LocalBoxFuture;
2019-03-02 06:51:32 +00:00
2021-06-17 16:57:58 +00:00
use crate::{
guard::{self, Guard},
handler::{Handler, HandlerService},
service::{ServiceRequest, ServiceResponse},
Error, FromRequest, HttpResponse, Responder,
};
2019-03-02 06:51:32 +00:00
2017-12-05 00:09:22 +00:00
/// 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 {
2021-02-27 21:00:36 +00:00
service: BoxServiceFactory<(), ServiceRequest, ServiceResponse, Error, ()>,
2019-07-17 09:48:37 +00:00
guards: Rc<Vec<Box<dyn Guard>>>,
2017-12-05 00:09:22 +00:00
}
impl Route {
2019-03-03 08:57:48 +00:00
/// Create new route which matches any request.
#[allow(clippy::new_without_default)]
pub fn new() -> Route {
Route {
2021-02-27 21:00:36 +00:00
service: boxed::factory(HandlerService::new(HttpResponse::NotFound)),
2019-03-03 20:09:38 +00:00
guards: Rc::new(Vec::new()),
}
2019-03-02 06:51:32 +00:00
}
2019-07-17 09:48:37 +00:00
pub(crate) fn take_guards(&mut self) -> Vec<Box<dyn Guard>> {
2020-05-17 01:54:42 +00:00
std::mem::take(Rc::get_mut(&mut self.guards).unwrap())
}
2019-03-02 06:51:32 +00:00
}
impl ServiceFactory<ServiceRequest> for Route {
2019-03-02 06:51:32 +00:00
type Response = ServiceResponse;
type Error = Error;
2021-02-27 21:00:36 +00:00
type Config = ();
type Service = RouteService;
2021-02-27 21:00:36 +00:00
type InitError = ();
type Future = LocalBoxFuture<'static, Result<Self::Service, Self::InitError>>;
2019-03-02 06:51:32 +00:00
2019-12-02 15:37:13 +00:00
fn new_service(&self, _: ()) -> Self::Future {
2021-02-27 21:00:36 +00:00
let fut = self.service.new_service(());
let guards = self.guards.clone();
2019-03-02 06:51:32 +00:00
2021-02-27 21:00:36 +00:00
Box::pin(async move {
let service = fut.await?;
Ok(RouteService { service, guards })
})
2017-12-05 00:09:22 +00:00
}
}
pub struct RouteService {
2021-02-27 21:00:36 +00:00
service: BoxService<ServiceRequest, ServiceResponse, Error>,
2019-07-17 09:48:37 +00:00
guards: Rc<Vec<Box<dyn Guard>>>,
2019-03-02 06:51:32 +00:00
}
impl RouteService {
pub fn check(&self, req: &mut ServiceRequest) -> bool {
2019-03-03 20:09:38 +00:00
for f in self.guards.iter() {
if !f.check(req.head()) {
2018-04-13 23:02:01 +00:00
return false;
2017-12-05 00:09:22 +00:00
}
}
true
}
2019-03-02 06:51:32 +00:00
}
2017-12-05 00:09:22 +00:00
impl Service<ServiceRequest> for RouteService {
2019-03-02 06:51:32 +00:00
type Response = ServiceResponse;
type Error = Error;
2019-11-20 17:33:22 +00:00
type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;
2019-03-02 06:51:32 +00:00
2021-02-27 21:00:36 +00:00
actix_service::forward_ready!(service);
2017-12-05 00:09:22 +00:00
fn call(&self, req: ServiceRequest) -> Self::Future {
2020-12-06 11:42:15 +00:00
self.service.call(req)
2018-01-10 04:00:18 +00:00
}
2019-03-02 06:51:32 +00:00
}
2018-01-10 04:00:18 +00:00
impl Route {
2019-03-03 20:09:38 +00:00
/// Add method guard to the route.
2017-12-20 06:36:06 +00:00
///
/// ```
2017-12-20 06:36:06 +00:00
/// # use actix_web::*;
/// # fn main() {
/// App::new().service(web::resource("/path").route(
/// web::get()
/// .method(http::Method::CONNECT)
2019-03-03 20:09:38 +00:00
/// .guard(guard::Header("content-type", "text/plain"))
/// .to(|req: HttpRequest| HttpResponse::Ok()))
/// );
2017-12-20 06:36:06 +00:00
/// # }
/// ```
2019-03-02 06:51:32 +00:00
pub fn method(mut self, method: Method) -> Self {
2019-03-03 20:09:38 +00:00
Rc::get_mut(&mut self.guards)
.unwrap()
2019-03-03 20:09:38 +00:00
.push(Box::new(guard::Method(method)));
2017-12-05 00:09:22 +00:00
self
}
2019-03-03 20:09:38 +00:00
/// Add guard to the route.
2019-03-02 06:51:32 +00:00
///
/// ```
2019-03-02 06:51:32 +00:00
/// # use actix_web::*;
/// # fn main() {
/// App::new().service(web::resource("/path").route(
/// web::route()
2019-03-03 20:09:38 +00:00
/// .guard(guard::Get())
/// .guard(guard::Header("content-type", "text/plain"))
/// .to(|req: HttpRequest| HttpResponse::Ok()))
/// );
2019-03-02 06:51:32 +00:00
/// # }
/// ```
2019-03-03 20:09:38 +00:00
pub fn guard<F: Guard + 'static>(mut self, f: F) -> Self {
Rc::get_mut(&mut self.guards).unwrap().push(Box::new(f));
2019-03-02 06:51:32 +00:00
self
2017-12-05 00:09:22 +00:00
}
2019-03-03 20:09:38 +00:00
/// Set handler function, use request extractors for parameters.
2018-03-27 06:10:31 +00:00
///
/// # Examples
/// ```
/// use actix_web::{web, http, App};
/// use serde::Deserialize;
2018-03-27 06:10:31 +00:00
///
/// #[derive(Deserialize)]
/// struct Info {
/// username: String,
/// }
///
/// /// extract path info using serde
2019-11-21 15:34:04 +00:00
/// async fn index(info: web::Path<Info>) -> String {
2019-03-03 20:09:38 +00:00
/// format!("Welcome {}!", info.username)
2018-03-27 06:10:31 +00:00
/// }
///
/// fn main() {
/// let app = App::new().service(
/// web::resource("/{username}/index.html") // <- define path parameters
/// .route(web::get().to(index)) // <- register handler
2019-03-03 20:09:38 +00:00
/// );
2018-03-27 06:10:31 +00:00
/// }
/// ```
///
2018-10-02 04:16:56 +00:00
/// It is possible to use multiple extractors for one handler function.
///
/// ```
/// # use std::collections::HashMap;
/// # use serde::Deserialize;
2019-03-07 19:43:46 +00:00
/// use actix_web::{web, App};
///
/// #[derive(Deserialize)]
/// struct Info {
/// username: String,
/// }
///
/// /// extract path info using serde
2019-11-21 15:34:04 +00:00
/// async fn index(path: web::Path<Info>, query: web::Query<HashMap<String, String>>, body: web::Json<Info>) -> String {
2019-03-03 20:09:38 +00:00
/// format!("Welcome {}!", path.username)
/// }
///
/// fn main() {
/// let app = App::new().service(
/// web::resource("/{username}/index.html") // <- define path parameters
/// .route(web::get().to(index))
2019-03-03 20:09:38 +00:00
/// );
/// }
/// ```
2020-12-26 21:46:19 +00:00
pub fn to<F, T, R>(mut self, handler: F) -> Self
2018-06-21 05:47:01 +00:00
where
2020-12-26 21:46:19 +00:00
F: Handler<T, R>,
T: FromRequest + 'static,
2020-12-26 21:46:19 +00:00
R: Future + 'static,
R::Output: Responder + 'static,
2018-01-10 04:00:18 +00:00
{
2021-02-27 21:00:36 +00:00
self.service = boxed::factory(HandlerService::new(handler));
2019-03-03 08:57:48 +00:00
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>>;
///
/// 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
}
2018-01-10 04:00:18 +00:00
}
2019-03-11 01:33:47 +00:00
#[cfg(test)]
mod tests {
2021-06-17 16:57:58 +00:00
use std::{convert::Infallible, time::Duration};
2019-03-25 21:33:34 +00:00
use actix_rt::time::sleep;
use bytes::Bytes;
use futures_core::future::LocalBoxFuture;
use serde::Serialize;
2019-03-25 21:33:34 +00:00
use crate::dev::{always_ready, fn_factory, fn_service, Service};
use crate::http::{header, Method, StatusCode};
use crate::service::{ServiceRequest, ServiceResponse};
2019-11-26 05:25:50 +00:00
use crate::test::{call_service, init_service, read_body, TestRequest};
use crate::{error, web, App, HttpResponse};
2019-03-11 01:33:47 +00:00
#[derive(Serialize, PartialEq, Debug)]
struct MyObject {
name: String,
}
2019-11-26 05:25:50 +00:00
#[actix_rt::test]
async fn test_route() {
let srv = init_service(
2019-11-26 05:25:50 +00:00
App::new()
.service(
web::resource("/test")
.route(web::get().to(HttpResponse::Ok))
2020-05-21 08:56:53 +00:00
.route(web::put().to(|| async {
Err::<HttpResponse, _>(error::ErrorBadRequest("err"))
2019-11-26 05:25:50 +00:00
}))
2020-05-21 08:56:53 +00:00
.route(web::post().to(|| async {
sleep(Duration::from_millis(100)).await;
2021-06-17 16:57:58 +00:00
Ok::<_, Infallible>(HttpResponse::Created())
2019-11-26 05:25:50 +00:00
}))
2020-05-21 08:56:53 +00:00
.route(web::delete().to(|| async {
sleep(Duration::from_millis(100)).await;
2020-05-21 08:56:53 +00:00
Err::<HttpResponse, _>(error::ErrorBadRequest("err"))
2019-11-26 05:25:50 +00:00
})),
)
2020-05-21 08:56:53 +00:00
.service(web::resource("/json").route(web::get().to(|| async {
sleep(Duration::from_millis(25)).await;
2020-05-21 08:56:53 +00:00
web::Json(MyObject {
name: "test".to_string(),
})
2019-11-26 05:25:50 +00:00
}))),
)
.await;
let req = TestRequest::with_uri("/test")
.method(Method::GET)
.to_request();
let resp = call_service(&srv, req).await;
2019-11-26 05:25:50 +00:00
assert_eq!(resp.status(), StatusCode::OK);
let req = TestRequest::with_uri("/test")
.method(Method::POST)
.to_request();
let resp = call_service(&srv, req).await;
2019-11-26 05:25:50 +00:00
assert_eq!(resp.status(), StatusCode::CREATED);
let req = TestRequest::with_uri("/test")
.method(Method::PUT)
.to_request();
let resp = call_service(&srv, req).await;
2019-11-26 05:25:50 +00:00
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;
2019-11-26 05:25:50 +00:00
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;
2019-11-26 05:25:50 +00:00
assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED);
let req = TestRequest::with_uri("/json").to_request();
let resp = call_service(&srv, req).await;
2019-11-26 05:25:50 +00:00
assert_eq!(resp.status(), StatusCode::OK);
let body = read_body(resp).await;
assert_eq!(body, Bytes::from_static(b"{\"name\":\"test\"}"));
2019-03-11 01:33:47 +00:00
}
#[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!")
);
}
2019-03-11 01:33:47 +00:00
}