如何在Akka HTTP中嵌套路由?

时间:2018-09-24 08:20:57

标签: scala akka-http

我正在尝试编写一系列简单的路线,这就是我想发生的事情:

SomeType应该打印“ hello get”

ts.to_pydatetime()应该打印“你好帖子”

GET /应该显示“ hello foo get”

POST /应该显示“ hello foo get”

这就是我所拥有的:

GET /foo

这适用于POST /fooval route = pathSingleSlash { get(complete("hello get")) ~ post(complete("hello post"))~ path("foo") { get(complete("hello foo get"))~ post(complete("hello foo post")) } } ,但同时在GET / 404上执行GET和POST。

我已经尝试了几乎所有内容,却不知道该怎么办。关于此文档,很难理解。

有人可以给我任何指示吗?

2 个答案:

答案 0 :(得分:1)

可以请您尝试一下。它为我工作。

val route1 = path("foo") {
        get(complete("hello foo get")) ~
          post(complete("hello foo post"))
      }

  val route = pathSingleSlash {
    get(complete("hello get")) ~
      post(complete("hello post"))
  }

  val finalRoute = route ~ route1

,并在路由绑定语句中使用finalRoute。

val bindingFuture = Http().bindAndHandle(finalRoute, "localhost", 8085)

答案 1 :(得分:1)

我建议以这种方式构造路径以最大程度地提高可读性:

get & pathEndOrSingleSlash {
  complete("hello get")
} ~
post & pathEndOrSingleSlash {
  complete("hello post")
} ~
get & path("foo") & pathEndOrSingleSlash {
  complete("hello foo get")
}
post & path("foo") & pathEndOrSingleSlash {
  complete("hello foo post")
}