【问题标题】:How to change HTTP status code of AsyncResult using Scalatra如何使用 Scalatra 更改 AsyncResult 的 HTTP 状态代码
【发布时间】:2015-06-18 19:50:40
【问题描述】:

我创建了一个简单的控制器(下面的代码经过混淆和简化,假设 ask 返回带有消息的未来)。我正在尝试做的是将 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

Akka 2.3.9

【问题讨论】:

    标签: scala akka scalatra


    【解决方案1】:

    在 Scalatra FutureSupport mixin 中进行了一些挖掘后,我发现:

    implicit val response: HttpServletResponse = scalatraContext.response
    

    定义为 AsyncResult 的成员,它允许我在 onComplete 回调中更改 HTTP 请求的状态代码。

    【讨论】:

      【解决方案2】:

      如果你愿意,你实际上可以将Future[ActionResult] 退回到is。然后在Future里面可以返回Ok()

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-01-28
        • 1970-01-01
        • 1970-01-01
        • 2015-09-12
        • 1970-01-01
        • 2022-01-25
        • 1970-01-01
        相关资源
        最近更新 更多