3

I need to add a route to actix_web only if an external condition is met. Since actix_web's App uses a builder pattern and each call to App::route consumes the app instance, I can't seem to find a reasonable way of adding a route conditionally.

Example (that does not work, but illustrates what I'm up to):

let mut app = App::new()
  .app_data(server_data.clone())
  .route(
    "/shoobidoo",
    web::get().to(handlers::shoobidoo_handler)
  );

  if let Some(login_path) = &config.login_path {
    app.route(
      login_path,
      web::get().to(handlers::login)
    );
  }

I could use a guard, but this seems weird and over complicated, since it would mean that I still have to add the handler with a dummy path.

Markus
  • 2,412
  • 29
  • 28

1 Answers1

2

Since route not just consumes self but also returns it, you can re-assign it to app:

let mut app = App::new()
    .app_data(server_data.clone())
    .route("/shoobidoo", web::get().to(handlers::shoobidoo_handler));

if let Some(login_path) = &config.login_path {
    app = app.route(login_path, web::get().to(handlers::login));
}
Chayim Friedman
  • 47,971
  • 5
  • 48
  • 77