【发布时间】:2016-08-15 00:00:38
【问题描述】:
我正在使用这本书 Reactive Web Applications: Covers Play, Akka, and Reactive Streams 在 Play 上磨牙。第 4 章,除其他外,教授如何编写过滤器,但书中显示的代码无法编译,因为在 Play 2.4.x 中,Result.body 曾经是 Enumerator[Array[Byte]],而在 2.5.x 中是 @ 987654327@.
我的过滤器版本如下:
class ScoreFilter @Inject()(implicit val mat: Materializer, ec: ExecutionContext) extends Filter {
override def apply(nextFilter: (RequestHeader) => Future[Result])(rh: RequestHeader) =
nextFilter(rh).map { result =>
if (result.header.status == OK || result.header.status == NOT_ACCEPTABLE) {
val correct = result.session(rh).get("correct").getOrElse(0)
val wrong = result.session(rh).get("wrong").getOrElse(0)
val score = s"\nYour current score is: $correct correct " +
s"answers and $wrong wrong answers"
val contentType = result.body.contentType
val scoreByteString = ByteString(score.getBytes(UTF_8))
val maybeNewBody = result.body.consumeData.map(_.concat(scoreByteString))
import scala.concurrent.duration._
val newBody = Await.result(maybeNewBody, 10 seconds)
result.copy(body = Strict(newBody, contentType))
} else {
result
}
}
}
在书中:
// result.body returns a play.api.http.HttpEntity which doesn't have an andThen method
val newBody = result.body andThen Enumerator(score.getBytes(UTF_8))
result.copy(body = newBody)
如您所见,我的过滤器版本有效,但它会阻止未来。我想知道是否有更好的方法可以在不阻塞的情况下做到这一点?
P.S.:在将我的问题视为重复问题之前,请注意我已经阅读了以下所有主题,它们将响应正文转换为字符串,这不是我想要的。
Scala play http filters: how to find the request body
Play framework filter that modifies json request and response
【问题讨论】:
标签: scala playframework akka servlet-filters playframework-2.5