Skip to content

Instantly share code, notes, and snippets.

@johanandren
Created September 11, 2017 08:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save johanandren/abb594cafd10a266138730180ddf93c9 to your computer and use it in GitHub Desktop.
Save johanandren/abb594cafd10a266138730180ddf93c9 to your computer and use it in GitHub Desktop.
Example swapping a complete route tree
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.server._
import akka.stream.ActorMaterializer
class DynamicTree extends Directives {
@volatile private var root: Route = reject
private val apply = (requestContext: RequestContext) => root(requestContext)
def dynamicRoot(initialRoute: Route): Route = {
root = initialRoute.apply
apply
}
def swapDynamic(newRoot: Route): Unit = {
root = newRoot.apply
}
}
object SwapRoutes extends App {
implicit val system = ActorSystem()
implicit val mat = ActorMaterializer()
import Directives._
val dynamicTree = new DynamicTree
val alternative: Route = get {
complete("alternative everything")
}
val route =
dynamicTree.dynamicRoot(
get {
concat(
path("swap") {
dynamicTree.swapDynamic(alternative)
complete("swapped behaviors")
},
// all other paths
complete("initial tree")
)
}
)
Http().bindAndHandle(route, "127.0.0.1", 8080)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment