喷涂授权指令未按预期工作?

Spray authorized directive not working as expected?

我是 Spray 的新手,所以我猜这只是我没有正确理解框架的工作原理。但是,我在尝试处理时遇到了似乎很奇怪的行为。此问题具体引用 this documentation on directives,但它也可能适用于其他自定义指令。

当我尝试使用 Spray 附带的 authorize 指令时,HTTP 响应根据返回值正确显示。也就是说,当 authorize 的返回值是 false 时,我得到 403 Forbidden,而当它是 true 时,我得到 200 OK。但是,似乎传递给它的函数仍然执行,即使它看起来不应该执行。

请查看我创建的用于测试的 this SBT project。它准确地展示了我的问题,因此,希望它有助于解决我的问题。 运行 与:

sbt test

默认情况下您应该看到的输出应该与以下内容非常相似:

[info] Test:
[info] route
[info] - should succeed and have side effects
[info] - should fail and not have side effects *** FAILED ***
[info]   1 did not equal 0 (Test.scala:28)
[info] Run completed in 779 milliseconds.
[info] Total number of tests run: 2
[info] Suites: completed 1, aborted 0
[info] Tests: succeeded 1, failed 1, canceled 0, ignored 0, pending 0
[info] *** 1 TEST FAILED ***

同样,我担心的是:为什么即使请求被拒绝,传递到 authorizedDirective0 的函数主体也会执行?

(如果这是重复的,我深表歉意。我在这里的其他地方找不到类似的问题,但如果你能找到的话,请关闭这个问题)

路由 api 的语义在 http://spray.io/documentation/1.2.3/spray-routing/advanced-topics/understanding-dsl-structure/ 中进行了解释。这里相关的关键点:

The mistake of putting custom logic inside of the route structure, but outside of a leaf-level route, and expecting it to be executed at request-handling time, is probably the most frequent error seen by new spray users.

参考页面中提供了两个对比示例。在此示例中,println 发生一次(在路由创建时):

val route: Route = get {
  println("MARK")
  complete("yeah")
}

在这个例子中,每个请求都会出现 println:

val route: Route = get {
  complete {
    println("MARK")
    "yeah"
  }
}