【发布时间】:2014-04-11 08:39:59
【问题描述】:
我正在学习 Scala,但还不熟悉使用 Spray 框架构建一些 REST-API 应用程序并面临一个问题:我所有的 HTTP 响应都应该有特定的标头 (Access-Control-Allow-Origin)。所以我不知道如何将它设置为一次所有应用程序的响应,而不是每个响应。
我的路线是这样的:
trait Statistics extends HttpService { self: StatisticModuleLike =>
implicit def MM: MarshallerM[Future]
lazy val statisticsRoute =
path("statistics" / "applications" / Segment / Segment ) { (measure, period) =>
get {
respondWithHeader(RawHeader("Access-Control-Allow-Origin", "*")) {
complete {
getAppCount(MeasureType.withName(measure), period.toInt)
}
}
}
} ~
path("statistics" / "approvals" / Segment / Segment ) { (measure, period) =>
get {
respondWithHeader(RawHeader("Access-Control-Allow-Origin", "*")) {
complete {
getApproval(MeasureType.withName(measure), period.toInt)
}
}
}
} ~
path("statistics" / "amounts" / Segment / Segment ) { (measure, period) =>
get {
respondWithHeader(RawHeader("Access-Control-Allow-Origin", "*")) {
complete {
getAmount(MeasureType.withName(measure), period.toInt)
}
}
}
} ~
path("statistics" / "sellers" / "snooze") {
get {
respondWithHeader(RawHeader("Access-Control-Allow-Origin", "*")) {
complete {
getSellerSnooze(MeasureType.withName("Month"), 100)
}
}
}
} ~
path("statistics" / "sellers" / "snooze" / Segment / Segment ) { (measure, period) =>
get {
respondWithHeader(RawHeader("Access-Control-Allow-Origin", "*")) {
complete {
getSellerSnooze(MeasureType.withName(measure), period.toInt)
}
}
}
} ~
path("statistics" / "sellers" / "growing" / Segment / Segment ) { (measure, period) =>
get {
parameter('percent.as[Int] ? 0) { percent =>
respondWithHeader(RawHeader("Access-Control-Allow-Origin", "*")) {
complete {
getSellerDynamic(MeasureType.withName(measure), period.toInt, DynamicTrendType.withName("Growing"), percent)
}
}
}
}
} ~
path("statistics" / "sellers" / "falling" / Segment / Segment ) { (measure, period) =>
get {
parameters('percent.as[Int] ? 0, 'average.as[Int] ? 0) { (percent, average) =>
respondWithHeader(RawHeader("Access-Control-Allow-Origin", "*")) {
complete {
getSellerDynamic(MeasureType.withName(measure), period.toInt, DynamicTrendType.withName("Falling"), percent)
}
}
}
}
}
}
如你所见,添加
respondWithHeader(RawHeader("Access-Control-Allow-Origin", "*"))
去每条路都不方便...
有什么可爱的方法可以解决这个问题吗?比如说,用一些自定义扩展 HttpService 并使用它而不是基本的?
【问题讨论】:
-
当然可以。您不喜欢扩展 HttpService 并对其进行自定义的解决方案?
-
@maks 对扩展 HttpService 有点不确定:我需要的功能只是响应自定义,而不是整个 HttpService... 所以我建议,必须有一种更短、更友好的方式来避免仅针对一些基本特征参数化扩展的基本组件。
标签: scala http-headers httpresponse spray