How to aggregate akka-http routes using a trait?

回眸只為那壹抹淺笑 提交于 2019-12-12 16:48:26

问题


I am trying to aggregate routes using a trait at runtime, so far I have

object SMController {
  def aggregateRoutes(actorSystem: ActorSystem): List[Route] = {
    val runtimeMirror = universe.runtimeMirror(getClass.getClassLoader)
    val reflections = new Reflections("com.example.api")
    val subclasses = reflections.getSubTypesOf(classOf[Routable])
    val routesList = new ListBuffer[Route]()

    for (i <- subclasses) {
      val module = runtimeMirror.staticModule(i.getName)
      val obj = runtimeMirror.reflectModule(module)
      val someTrait: Routable = obj.instance.asInstanceOf[Routable]
      routesList += someTrait.getAllRoutes(actorSystem)
    }

    routesList.toList
  }
}

obviously above code doesn't work as the List of items cannot be passed to Http().bindAndHandle.

So my question is, how can I parse the List[Routes] to a Http().bindAndHandle accepts or how can I dynamically load routes from subclasses of Routable?


回答1:


foldLeft: I have managed to foldLeft the routes and coalesce all the routes, as follows

val routes = SMController.aggregateRoutes(system)
val bindingFuture = Http().bindAndHandle(
        routes.tail.foldLeft(routes.head)((a, b) => a ~ b), "localhost", 8080)

reduceLeft:

routes.reduceLeft(_ ~ _)


来源:https://stackoverflow.com/questions/36247381/how-to-aggregate-akka-http-routes-using-a-trait

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!