Skip to content

Instantly share code, notes, and snippets.

@johanandren johanandren/SwapRoutes.scala Secret
Created Sep 11, 2017

Embed
What would you like to do?
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
You can’t perform that action at this time.