在 akka-http 指令中嵌套 CRUD 路径
Nesting CRUD paths in akka-http directives
我刚开始接触 Scala 和 Akka。我正在写一个小的 REST 服务。我正在尝试创建以下路径:
- GET localhost:8080/api/my-service(return资源集合)
- GET localhost:8080/api/my-service/6(return 具有指定 id 的资源)
- POST localhost:8080/api/my-service(在正文中创建包含数据的新资源)
- UPDATE localhost:8080/api/my-service/4(使用正文中的数据更新请求的资源)
- DELETE localhost:8080/api/my-service/5(删除指定id的资源)
我已经成功地创建了嵌套路径,但是只有获取集合的 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 ...
}
}
}
}
}
我刚开始接触 Scala 和 Akka。我正在写一个小的 REST 服务。我正在尝试创建以下路径:
- GET localhost:8080/api/my-service(return资源集合)
- GET localhost:8080/api/my-service/6(return 具有指定 id 的资源)
- POST localhost:8080/api/my-service(在正文中创建包含数据的新资源)
- UPDATE localhost:8080/api/my-service/4(使用正文中的数据更新请求的资源)
- DELETE localhost:8080/api/my-service/5(删除指定id的资源)
我已经成功地创建了嵌套路径,但是只有获取集合的 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 ...
}
}
}
}
}