将两条路线合二为一

Compose two routes into one

让我们考虑一个简化的例子。

def routes: Route = {
  pathPrefix("parent" / IntNumber) { (id) =>
    get {
      complete(id)
    } ~
    pathPrefix("child") { // this would be in separate file
      get {
        complete(s"parent/$id/child")
      }
    }
  }
}

我需要的是把

def childRoutes: Route = {
  pathPrefix("child") {
    get {
      complete(s"parent/$id/child")
    }
  }
}

到一个单独的文件中并将其组合到父路由中,但我不知道如何从父路由传播变量 id

路由是函数

使用 akka-http 时要记住的一件事是 Route 只是一个函数,from the documentation:

type Route = (RequestContext) ⇒ Future[RouteResult]

因此,您可以创建一个higher-order函数来实例化childRoute:

//Child.scala
val childRoute : (Int) => Route = 
  (id) => pathPrefix("child") {
    get {
      complete(s"parent/$id/child")
    }
  }

现在可以与parent组成:

//Parent.scala
val routes: Route = 
  pathPrefix("parent" / IntNumber) { (id) =>
    get{
      complete(id)
    } ~ childRoute(id)
  }

路线不一致

附带说明:您的 child 路线将永远无法到达。因为你正在用 child 组合 get { complete(id) },而 child 也有 get,所以你总是 return complete(id)complete(s"parent/$id/child") 永远不会被请求到达。