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

Nesting CRUD paths in akka-http directives

我刚开始接触 Scala 和 Akka。我正在写一个小的 REST 服务。我正在尝试创建以下路径:

我已经成功地创建了嵌套路径,但是只有获取集合的 GET(要点中的第一个示例)才是 return 结果。路径中带有 id 的 GET 示例是 returning 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 ...
                }
            }
        }
    }
}