如何从 Cask 中的 RawDecorator 返回响应对象

问题描述 投票:0回答:1

我正在尝试使用 Cask HTTP 框架中的 RawDecorator 来验证 devKey,但我不确定我是否理解当 devKey 无效时如何返回错误响应。这是我正在尝试的:

class AuthenticatedDevKey extends RawDecorator
{
    override def wrapFunction(ctx: Request, delegate: Delegate) =
    {
        // Get the devKey from header
        val devKey = ctx.headers.getOrElse("devKey", "").toString
        // Check if this is a valid devKey
        if(devKey != "" && MicroServiceManager.isExistingDevKey(devKey))
            delegate(Map("devKey" -> devKey))
        else
            cask.Response("Invalid DevKey", statusCode = StatusCodes.UNAUTHORIZED)

    }
}

这给了我一个类型不匹配错误。文档(https://com-lihaoyi.github.io/cask/index.html#extending-endpoints-with-decorators)说我可以返回响应,但我还没有看到任何这样的例子。 如何返回带有错误状态代码的响应?

scala cask
1个回答
0
投票

不确定您收到的完整错误消息是什么,但根据提供的示例,我认为您需要返回

Left[cask.Response]
以避免进一步处理,因为您在 Cask - 使用装饰器扩展端点共享的链接中有详细说明

使用装饰器扩展端点

返回

Either[Response, cask.Decor[Any]]
。返回
Left
可以让您提前使用固定的
cask.Response
退出,避免进一步处理。返回
Right
提供参数名称和值的映射,然后将其传递到连续参数列表中的端点函数(如上所示),以及端点终止后运行的可选清理函数。

所以,你的代码应该是

class AuthenticatedDevKey extends RawDecorator {
  override def wrapFunction(ctx: Request, delegate: Delegate) = {
    // Get the devKey from header
    val devKey = ctx.headers.getOrElse("devKey", "").toString
    // Check if this is a valid devKey
    if(devKey != "" && MicroServiceManager.isExistingDevKey(devKey))
      delegate(Map("devKey" -> devKey))
    else
      Left(cask.Response("Invalid DevKey", statusCode = StatusCodes.UNAUTHORIZED))
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.