diff --git a/CHANGES.md b/CHANGES.md index ec09de2ac..c379c1545 100644 --- a/CHANGES.md +++ b/CHANGES.md @@ -3,10 +3,12 @@ ## Unreleased - 2021-xx-xx ### Added - `GuardContext::header` [#2569] +- `ServiceConfig::configure` to allow easy nesting of configuration functions. [#1988] ### Changed - `HttpResponse` can now be used as a `Responder` with any body type. [#2567] +[#1988]: https://github.com/actix/actix-web/pull/1988 [#2567]: https://github.com/actix/actix-web/pull/2567 [#2569]: https://github.com/actix/actix-web/pull/2569 diff --git a/src/config.rs b/src/config.rs index d68374387..2482ee6c4 100644 --- a/src/config.rs +++ b/src/config.rs @@ -215,6 +215,17 @@ impl ServiceConfig { self } + /// Run external configuration as part of the application building process + /// + /// Counterpart to [`App::configure()`](crate::App::configure) that allows for easy nesting. + pub fn configure(&mut self, f: F) -> &mut Self + where + F: FnOnce(&mut ServiceConfig), + { + f(self); + self + } + /// Configure route for a specific path. /// /// Counterpart to [`App::route()`](crate::App::route). @@ -264,7 +275,7 @@ mod tests { use super::*; use crate::http::{Method, StatusCode}; - use crate::test::{call_service, init_service, read_body, TestRequest}; + use crate::test::{assert_body_eq, call_service, init_service, read_body, TestRequest}; use crate::{web, App, HttpRequest, HttpResponse}; // allow deprecated `ServiceConfig::data` @@ -363,4 +374,22 @@ mod tests { let resp = call_service(&srv, req).await; assert_eq!(resp.status(), StatusCode::OK); } + + #[actix_rt::test] + async fn nested_service_configure() { + fn cfg_root(cfg: &mut ServiceConfig) { + cfg.configure(cfg_sub); + } + + fn cfg_sub(cfg: &mut ServiceConfig) { + cfg.route("/", web::get().to(|| async { "hello world" })); + } + + let srv = init_service(App::new().configure(cfg_root)).await; + + let req = TestRequest::with_uri("/").to_request(); + let res = call_service(&srv, req).await; + assert_eq!(res.status(), StatusCode::OK); + assert_body_eq!(res, b"hello world"); + } }