2

对于 POST 和 PUT 请求,我使用以下语法:

put {
  entity(as[CaseClass]) { entity =>
     returnsOption(entity).map(result => complete{(Created, result)})
       .getOrElse(complete{(NotFound, "I couldn't find the parent resource you're modifying")})
  }
}

现在对于 GET 请求,我正在尝试做同样的事情,但我无法让它与我的 PUT 解决方案类似地工作。使用 GET 请求执行此操作的好方法是什么?

更新:我使用以下 hack 来解决这个问题:

(get & parameters('ignored.?)) {
  //TODO find a way to do this without ignored parameters
  (ingored:Option[String]) => {
     returnsOption().map(result => complete(result))
       .getOrElse(complete{(NotFound, "")})
  }
 }

我希望使用() =>or可以实现类似的事情ctx =>,但这并不可行,因为它给编组带来了麻烦:

... could not find implicit value for evidence parameter of type spray.httpx.marshalling.Marshaller[(spray.http.StatusCodes.ClientError, String)]
    }).getOrElse(ctx.complete{(NotFound, "")})
                             ^

难道这与我使用spray-json的事实有关吗?

4

2 回答 2

15

例如,像这样使用HttpResponse

complete{
  HttpResponse(StatusCodes.OK, HttpBody(ContentType(`text/html`), "test test: " + System.currentTimeMillis.toString))
}

更新:我已经使用 Spray 有一段时间了。原来有更好的方法:

complete {
  StatusCodes.BandwidthLimitExceeded -> MyCustomObject("blah blah")
}
于 2013-05-06T05:11:02.397 回答
4

此代码应该可以工作:

get {
  ctx =>  
     ctx.complete(returnsOption())
 }

如果一开始不使用ctx =>,您的代码可能只会在路由构建时执行。

在这里您可以找到一些解释:了解 DSL 结构

于 2013-04-01T15:32:21.100 回答