Spray Routing 未正确匹配 HTTP 方法

Spray Routing not matching HTTP Method correctly

我正在使用 Spray Routing 尝试使用不同的 HTTP 方法来匹配路由,但是当我发出 GET 请求时,它实际上经过了 DELETE、PUT 和 GET。我认为 deleteput 拒绝所有不是 HTTP DELETE 或 HTTP PUT 的请求。

这是我的基本代码:

path(Segment ~ Slash.?) { id =>
  delete {
    println("Hello from DELETE")
    //do stuff for delete
    complete("done for DELETE")
  } ~
  put {
    println("Hello from PUT")
    //do stuff for put
    complete("done for PUT")
  } ~
  get {
    println("Hello from GET")
    //do stuff for get
    complete("done for GET")
  }
}

如果我触发 GET 请求,我可以看到应用打印:

Hello from DELETE
Hello from PUT
Hello from GET

我是否错过了任何 return 电话或其他什么?

不,您的代码(几乎)正确。

问题是,在 spray 中,存在于方法匹配器中但不存在于提取中的代码(指令之一 "extracting" 某些东西,例如 "parameters" 或 "segment") 一直执行。

在你的例子中,你正确地匹配了路径提取器,但之后路由执行了所有的 get put delete 等。

解决方案是在 get/put 等下方添加“dynamic”关键字。缺点是会损失一些性能。

path(...) {
  get {
    dynamic {
      ...
    }
  }
}

或者,您可以重新排列代码,使方法匹配器位于顶层,路径提取器位于其下

get {
   path(...) {
     ...
   }
}