Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add ServiceConfig::default_service #2338

Closed
Closed
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 4 additions & 2 deletions CHANGES.md
Expand Up @@ -3,8 +3,10 @@
## Unreleased - 2021-xx-xx
### Added
* Re-export actix-service `ServiceFactory` in `dev` module. [#2325]
* Add `ServiceConfig::default_service`. [#2338]

[#2325]: https://github.com/actix/actix-web/pull/2325
[#2338]: https://github.com/actix/actix-web/pull/2338


## 4.0.0-beta.8 - 2021-06-26
Expand Down Expand Up @@ -169,7 +171,7 @@
### Removed
* Public modules `middleware::{normalize, err_handlers}`. All necessary middleware structs are now
exposed directly by the `middleware` module.
* Remove `actix-threadpool` as dependency. `actix_threadpool::BlockingError` error type can be imported
* Remove `actix-threadpool` as dependency. `actix_threadpool::BlockingError` error type can be imported
from `actix_web::error` module. [#1878]

[#1812]: https://github.com/actix/actix-web/pull/1812
Expand Down Expand Up @@ -262,7 +264,7 @@

## 3.0.0-beta.4 - 2020-09-09
### Added
* `middleware::NormalizePath` now has configurable behavior for either always having a trailing
* `middleware::NormalizePath` now has configurable behavior for either always having a trailing
slash, or as the new addition, always trimming trailing slashes. [#1639]

### Changed
Expand Down
4 changes: 4 additions & 0 deletions src/app.rs
Expand Up @@ -205,6 +205,10 @@ where
self.services.extend(cfg.services);
self.external.extend(cfg.external);
self.extensions.extend(cfg.app_data);
if let Some(default) = cfg.default {
self.default = Some(default);
}

Comment on lines +208 to +211
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should have this for Scope::configure as well.

self
}

Expand Down
41 changes: 40 additions & 1 deletion src/config.rs
Expand Up @@ -3,7 +3,7 @@ use std::rc::Rc;

use actix_http::Extensions;
use actix_router::ResourceDef;
use actix_service::{boxed, IntoServiceFactory, ServiceFactory};
use actix_service::{boxed, IntoServiceFactory, ServiceFactory, ServiceFactoryExt};

use crate::data::Data;
use crate::error::Error;
Expand Down Expand Up @@ -185,6 +185,7 @@ pub struct ServiceConfig {
pub(crate) services: Vec<Box<dyn AppServiceFactory>>,
pub(crate) external: Vec<ResourceDef>,
pub(crate) app_data: Extensions,
pub(crate) default: Option<Rc<HttpNewService>>,
}

impl ServiceConfig {
Expand All @@ -193,6 +194,7 @@ impl ServiceConfig {
services: Vec::new(),
external: Vec::new(),
app_data: Extensions::new(),
default: None,
}
}

Expand All @@ -213,6 +215,28 @@ impl ServiceConfig {
self
}

/// Default service to be used if no matching resource could be found.
///
/// Counterpart to [`App::default_service()`](crate::App::default_service).
pub fn default_service<F, U>(&mut self, f: F) -> &mut Self
where
F: IntoServiceFactory<U, ServiceRequest>,
U: ServiceFactory<
ServiceRequest,
Config = (),
Response = ServiceResponse,
Error = Error,
> + 'static,
U::InitError: std::fmt::Debug,
{
// create and configure default resource
self.default = Some(Rc::new(boxed::factory(f.into_factory().map_init_err(
|e| log::error!("Can not construct default service: {:?}", e),
))));

self
}

/// Configure route for a specific path.
///
/// Counterpart to [`App::route()`](crate::App::route).
Expand Down Expand Up @@ -341,6 +365,21 @@ mod tests {
assert_eq!(body, Bytes::from_static(b"https://youtube.com/watch/12345"));
}

#[actix_rt::test]
async fn test_default_service() {
let srv = init_service(App::new().configure(|cfg| {
cfg.default_service(
web::get().to(|| HttpResponse::NotFound().body("four oh four")),
);
}))
.await;
let req = TestRequest::with_uri("/path/i/did/not-configure").to_request();
let resp = call_service(&srv, req).await;
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
let body = read_body(resp).await;
assert_eq!(body, Bytes::from_static(b"four oh four"));
}

#[actix_rt::test]
async fn test_service() {
let srv = init_service(App::new().configure(|cfg| {
Expand Down