【问题标题】:How to nest routes in Akka HTTP?如何在 Akka HTTP 中嵌套路由?
【发布时间】:2018-09-24 08:20:57
【问题描述】:

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

GET / 应该打印“hello get”

POST / 应该打印“hello post”

GET /foo 应该打印“hello foo get”

POST /foo 应该打印“hello foo get”

这是我所拥有的:

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

这适用于GET /POST /,但在/foo 404 上进行GET 和POST。

我几乎尝试了所有方法,但不知道该怎么做。当涉及到这一点时,文档很难理解。

谁能指点一下?

【问题讨论】:

  • path 匹配值到傻瓜路径,尝试使用 pathPrefix 代替 path

标签: scala akka-http


【解决方案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)

【讨论】:

    【解决方案2】:

    我建议以这种方式构建路径以获得最大的可读性:

    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")
    }
    

    【讨论】:

    • 我猜可读性是主观的:P 但很高兴知道这些选项,谢谢。
    • 它也不起作用,因为 pathpathSingleSlash 不作曲。无论如何get & path("foo") 应该足够了。
    猜你喜欢
    • 1970-01-01
    • 2021-12-23
    • 2018-08-15
    • 1970-01-01
    • 2017-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    相关资源
    最近更新 更多