【发布时间】:2018-11-06 14:55:21
【问题描述】:
在典型的 Akka Http DSL 样式中,我们有:
import akka.http.scaladsl.server.Directives._
然后在代码中你可能会看到类似
val routes = {
logRequestResult("akka-http-microservice") {
pathPrefix("ip") {
(get & path(Segment)) { ip =>
complete {
fetchIpInfo(ip).map[ToResponseMarshallable] {
case Right(ipInfo) => ipInfo
case Left(errorMessage) => BadRequest -> errorMessage
}
}
} ~
(post & entity(as[IpPairSummaryRequest])) { ipPairSummaryRequest =>
complete {
val ip1InfoFuture = fetchIpInfo(ipPairSummaryRequest.ip1)
val ip2InfoFuture = fetchIpInfo(ipPairSummaryRequest.ip2)
ip1InfoFuture.zip(ip2InfoFuture).map[ToResponseMarshallable] {
case (Right(info1), Right(info2)) => IpPairSummary(info1, info2)
case (Left(errorMessage), _) => BadRequest -> errorMessage
case (_, Left(errorMessage)) => BadRequest -> errorMessage
}
}
}
}
}
我不完全明白的是,例如(get & path(Segment)) { ip => 中的“get”是如何被识别为 MethodDirectives 特征的方法定义的。 所以我们输入 '(get ...' 并且 Scala 知道它来自 MethodDirectives,但是如何?
在我看来,使这项工作有效的原因似乎是 Scala 编译器的一个核心特性,这对我来说并不明显。
我总是对从 Java 迁移到 Scala 的人说,就像皈依一个新的宗教,有时你只需要相信 ;)
我知道当我发现时我会踢自己:(
【问题讨论】:
-
仍在调查这个问题,似乎 {} 中的任何内容都像 'val routes = {...}' 中的部分函数!情节变厚
-
我有点不明白为什么这个问题没人回答,可能是因为不清楚,或者这是一个愚蠢的问题或其他原因。