在这里回答我自己的问题,因为这花了我一天的时间来弄清楚,这是一个非常简单的问题,我认为其他人可能会遇到。
在使用REST创建RESTful-esk服务时,我希望将具有字母数字id的路由作为路径的一部分进行匹配。这就是我最初的开始:
case class APIPagination(val page: Option[Int], val perPage: Option[Int])
get {
pathPrefix("v0" / "things") {
pathEndOrSingleSlash {
parameters('page ? 0, 'perPage ? 10).as(APIPagination) { pagination =>
respondWithMediaType(`application/json`) {
complete("things")
}
}
} ~
path(Segment) { thingStringId =>
pathEnd {
complete(thingStringId)
} ~
pathSuffix("subthings") {
pathEndOrSingleSlash {
complete("subthings")
}
} ~
pathSuffix("othersubthings") {
pathEndOrSingleSlash {
complete("othersubthings")
}
}
}
}
} ~ //more routes...
这没有问题编译,但是当使用scalatest来验证路由结构是否正确时,我很惊讶地发现这种类型的输出:
"ThingServiceTests:"
"Thing Service Routes should not reject:"
- should /v0/things
- should /v0/things/thingId
- should /v0/things/thingId/subthings *** FAILED ***
Request was not handled (RouteTest.scala:64)
- should /v0/things/thingId/othersubthings *** FAILED ***
Request was not handled (RouteTest.scala:64)
我的路线有什么问题?
答案 0 :(得分:5)
我查看了许多资源like this SO Question和this blog post,但似乎无法找到有关将字符串ID用作路径结构的顶层部分的任何信息。在查看spray scaladoc之前,我查看documentation on Path matchers for a while以及在this important test (duplicated below)上击败我的头:
"pathPrefix(Segment)" should {
val test = testFor(pathPrefix(Segment) { echoCaptureAndUnmatchedPath })
"accept [/abc]" in test("abc:")
"accept [/abc/]" in test("abc:/")
"accept [/abc/def]" in test("abc:/def")
"reject [/]" in test()
}
这让我想到了几件事。我应该尝试使用pathPrefix
代替path
。所以我改变了我的路线:
get {
pathPrefix("v0" / "things") {
pathEndOrSingleSlash {
parameters('page ? 0, 'perPage ? 10).as(APIPagination) { pagination =>
respondWithMediaType(`application/json`) {
listThings(pagination)
}
}
} ~
pathPrefix(Segment) { thingStringId =>
pathEnd {
showThing(thingStringId)
} ~
pathPrefix("subthings") {
pathEndOrSingleSlash {
listSubThingsForMasterThing(thingStringId)
}
} ~
pathPrefix("othersubthings") {
pathEndOrSingleSlash {
listOtherSubThingsForMasterThing(thingStringId)
}
}
}
}
} ~
很高兴让我的所有测试通过并且路线结构正常运行。然后我更新它以使用Regex
匹配器代替:
pathPrefix(new scala.util.matching.Regex("[a-zA-Z0-9]*")) { thingStringId =>
并决定在SO上发布遇到类似问题的其他人。正如jrudolph在评论中指出的那样,这是因为Segment
期望匹配<Segment><PathEnd>
而不是在路径中间使用。这是pathPrefix
对