如何使用 Scalatra 更改 AsyncResult 的 HTTP 状态码
How to change HTTP status code of AsyncResult using Scalatra
我创建了一个简单的控制器(下面的代码经过混淆和简化,假设向 returns 询问未来的消息)。我想要做的是将 HTTP 代码从 200 以外的其他内容更改为(基于演员结果)。
当执行下面的代码时,我看到结果按预期返回,但是 200 而不是 404
get("/:id") {
new AsyncResult() {
val is: Future[_] = ask(actor, message)(timeout.toMillis)
is.onComplete { res =>
res match {
case Success(result:Any) => NotFound(result) //Not found is just an example of a different HTTP code other than 200
}
}
}
另一次尝试是
case Success(result:Any) => {
this.status_ = (404)
result
}
在这种情况下,我收到 NullPointerException,因为 response
(HTTPServletResponse) 为空,因为响应在单独的线程上。
TL;DR
如何在 Scalatra 中有条件地更改 AsyncResult/Future 的 HTTP 代码?
详情
Scala 2.11.6
Scalatra 2.3.0
阿卡 2.3.9
在 Scalatra FutureSupport
mixin 中进行一些挖掘后,我发现:
implicit val response: HttpServletResponse = scalatraContext.response
定义为 AsyncResult
的成员,它允许我在 onComplete 回调中更改 HTTP 请求的状态代码。
如果你愿意,你实际上可以 return Future[ActionResult]
到 is
。然后在 Future
里面你可以 return Ok()
我创建了一个简单的控制器(下面的代码经过混淆和简化,假设向 returns 询问未来的消息)。我想要做的是将 HTTP 代码从 200 以外的其他内容更改为(基于演员结果)。
当执行下面的代码时,我看到结果按预期返回,但是 200 而不是 404
get("/:id") {
new AsyncResult() {
val is: Future[_] = ask(actor, message)(timeout.toMillis)
is.onComplete { res =>
res match {
case Success(result:Any) => NotFound(result) //Not found is just an example of a different HTTP code other than 200
}
}
}
另一次尝试是
case Success(result:Any) => {
this.status_ = (404)
result
}
在这种情况下,我收到 NullPointerException,因为 response
(HTTPServletResponse) 为空,因为响应在单独的线程上。
TL;DR
如何在 Scalatra 中有条件地更改 AsyncResult/Future 的 HTTP 代码?
详情
Scala 2.11.6
Scalatra 2.3.0
阿卡 2.3.9
在 Scalatra FutureSupport
mixin 中进行一些挖掘后,我发现:
implicit val response: HttpServletResponse = scalatraContext.response
定义为 AsyncResult
的成员,它允许我在 onComplete 回调中更改 HTTP 请求的状态代码。
如果你愿意,你实际上可以 return Future[ActionResult]
到 is
。然后在 Future
里面你可以 return Ok()