简体   繁体   中英

How to conditionally add route paths in akka-http?

I've got a series of paths that look like;

path("slides" / Segment) { segment =>
  getFromDirectory(s"${cfg.slidesDir}/$segment")
} ~
path("foo" / Segment) { segment =>
  getFromDirectory(s"${cfg.mypyPursDir}/$segment")
} ~
path("foo" / "images" / Segment) { segment =>
  getFromDirectory(s"${cfg.mypyPursImageDir}/$segment")
}

Under certain runtime conditions, some of these may not be active (eg production versus dev system). How does one enable this conditionality? I can imagine encoding it with if-else if there was a "dummy path" that didn't do anything, for instance.

Create a List of all the routes you want using standard Scala filtering and List building operations. Then use concat to create a route that includes all the selected routes.

val allRoutes: List[Route] = ???
val activeRoutes = allRoutes.filter(???)

def route =
  concat(activeRoutes:_*)

I prefer concat to ~ for chaining routes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM