Skip to content

Commit

Permalink
Add ServiceConfig::configure (actix#1988)
Browse files Browse the repository at this point in the history
Co-authored-by: Rob Ede <[email protected]>
  • Loading branch information
mibac138 and robjtede authored Jan 5, 2022
1 parent 4ebf168 commit 2d11ab5
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
2 changes: 2 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
31 changes: 30 additions & 1 deletion src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<F>(&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).
Expand Down Expand Up @@ -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`
Expand Down Expand Up @@ -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");
}
}

0 comments on commit 2d11ab5

Please sign in to comment.