【发布时间】:2020-12-22 16:29:49
【问题描述】:
我想在 Akka HTTP 中创建一个复杂的指令,我可以在其中使用查询 /api/guitar?id=42 或路径 /api/guitar/42。我确实使用了两个指令并且它有效。但是,我想在一个指令中使用所有可以从 | 运算符中受益的指令。所以,我有这个代码:
import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.model.{ContentTypes, HttpEntity}
import akka.http.scaladsl.server.Directives._
import akka.http.scaladsl.server.Route
object ComplexDirectives {
def main(args: Array[String]): Unit = {
implicit val system = ActorSystem("ComplexDirectives")
val complexRoute: Route = path("api" / "guitar") {
(path("" / IntNumber) | parameter('id.as[Int])) { (itemNumber: Int) =>
get {
println(s"I found the guitar $itemNumber")
complete(HttpEntity(
ContentTypes.`text/html(UTF-8)`,
s"""
|<html>
| <body>I found the guitar $itemNumber!</body>
|</html>
|""".stripMargin
))
}
}
}
println("http GET localhost:8080/api/guitar?id=43")
println("http GET localhost:8080/api/guitar/42")
Http().newServerAt("localhost", 8080).bindFlow(complexRoute)
}
}
当我使用 HTTP GET 命令http GET localhost:8080/api/guitar?id=43 时,我得到了 id 为 43 的吉他。但是当我使用命令 http GET localhost:8080/api/guitar/43 时,我无法得到吉他。我还将指令更改为仅(path(IntNumber) | parameter('id.as[Int])),但不起作用。
【问题讨论】: