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

dan*_*yel 7 rest scala routes akka-http

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

  • GET localhost:8080/api/my-service(返回资源集合)
  • GET localhost:8080/api/my-service/6(返回指定id的资源)
  • POST localhost:8080/api/my-service(用正文中的数据创建新资源)
  • 更新localhost:8080/api/my-service/4(使用正文中的数据更新请求的资源)
  • 删除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 ...
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我已经在网上检查了很多解决方案,并从Akka本身进行了一些测试,但不知怎的,我在这里遗漏了一些东西.

dan*_*yel 10

我找到了解决方案.问题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 ...
                }
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)