gpt4 book ai didi

scala - 在 akka-http 指令中嵌套 CRUD 路径

转载 作者:行者123 更新时间:2023-12-04 11:00:49 26 4
gpt4 key购买 nike

我刚开始使用 Scala 和 Akka。我正在编写一个小型 REST 服务。我正在尝试创建以下路径:

  • GET localhost:8080/api/my-service(返回资源集合)
  • GET localhost:8080/api/my-service/6(返回指定id的资源)
  • POST localhost:8080/api/my-service(使用正文中的数据创建新资源)
  • UPDATE localhost:8080/api/my-service/4(用正文中的数据更新请求的资源)
  • DELETE localhost:8080/api/my-service/5(删除指定id的资源)

  • 我设法创建了嵌套路径,但是只有用于获取集合的 GET(项目符号中的第一个示例)返回结果。路径中带有 id 的示例 GET 返回 The requested resource could not be found.我尝试了许多不同的变体,但似乎没有任何效果。

    以下是我的路线摘录:
    val routes = {
    logRequestResult("my-service-api") {
    pathPrefix("api") {
    path("my-service") {
    get {
    pathEndOrSingleSlash {
    complete("end of the story")
    } ~
    pathPrefix(IntNumber) { id =>
    complete("Id: %d".format(id))
    }
    } ~
    (post & pathEndOrSingleSlash & entity(as[MyResource])) { myResourceBody =>
    // do something ...
    }
    }
    }
    }
    }

    我已经在网上检查了许多解决方案以及 Akka 本身的一些测试,但不知何故我在这里遗漏了一些东西。

    最佳答案

    我找到了解决方案。问题出在 path("my-service")部分。我已将其更改为 pathPrefix("my-service")现在两个 GET 路径都在工作。

    所以正确的路线设置应该是这样的。

    val routes = {
    logRequestResult("my-service-api") {
    pathPrefix("api") {
    pathPrefix("my-service") {
    get {
    pathEndOrSingleSlash {
    complete("end of the story")
    } ~
    pathPrefix(IntNumber) { id =>
    complete("Id: %d".format(id))
    }
    } ~
    (post & pathEndOrSingleSlash & entity(as[MyResource])) { myResourceBody =>
    // do something ...
    }
    }
    }
    }
    }

    关于scala - 在 akka-http 指令中嵌套 CRUD 路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45232215/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com