여러 시나리오에서 재사용하려는 경로 스 니펫이 있습니다.
val dirSegment = "licenses"
path( dirSegment ~ PathEnd ) {
redirect( dirSegment + "/", StatusCodes.MovedPermanently )
} ~
pathPrefix(dirSegment) {
path("") {
/* do something */
}
}
나는 이것을 지시문 (또는 매개 변수화 가능한 경로?)으로 바꾸고 싶습니다. 여기에서 다음과 같이 리디렉션 동작을 유지하는 흰색 dirSegment
대신 val 값과 임의의 추가 라우팅 / 코드를 path("") { /* do something */ }
지정할 수 있습니다.
directoryPath("licenses") {
path("") {
/* do something */
}
} ~
directoryPath("about") {
path("") {
/* do somthing else */
}
}
모든 반복없이 다음과 동일한 동작을하는 반면 :
val dirSegment = "licenses"
val anotherDir = "About"
path( dirSegment ~ PathEnd ) {
redirect(dirSegment + "/", StatusCodes.MovedPermanently )
} ~
pathPrefix(dirSegment) {
path("") {
/* do something */
}
} ~
path( anotherDir ~ PathEnd ) {
redirect(anotherDir + "/", StatusCodes.MovedPermanently )
} ~
pathPrefix(anotherDir) {
path("") {
/* do something else */
}
}
이 질문은 스프레이 라우팅에서 URL 끝에 슬래시를 자동으로 추가하는 방법의 일부 토론에서 영감을 얻었습니다 .
이에 대한 사용자 지정 지시문을 작성해야합니다.
// additional imports you may need
import shapeless.HNil
import spray.http.StatusCodes
import spray.routing.Directive0
import spray.routing.PathMatcher
이제 그게 끝났습니다.
/**
* Spray's PathEnd matches trailing optional slashes... we can't have that
* otherwise it will cause a redirect loop.
*/
object PathEndNoSlash extends PathMatcher[HNil] {
def apply(path: Path) = path match {
case Path.Empty ⇒ PathMatcher.Matched.Empty
case _ ⇒ PathMatcher.Unmatched
}
}
/**
* Custom directive that uses a redirect to add a trailing slashe to segment
* if the slash isn't present.
*/
def directoryPath(segment: String) = new Directive0 {
def happly(f: HNil ⇒ Route) =
// first, the redirect
pathPrefix(segment ~ PathEndNoSlash) {
redirect("/" + segment + "/", StatusCodes.MovedPermanently) } ~
// delegate actual work to nested directives
pathPrefix(segment).happly(f)
}
용법:
directoryPath("about") {
path("a") {
complete {
"this is /about/a"
}
} ~ path("b") {
complete {
"this is /about/b"
}
} ~ path(PathEnd) {
complete {
"this is /about/"
}
}
}
사용자가에 액세스 /about
하면로 전달되고 /about/
"this is / about /"이 표시됩니다. 중첩 된 경로 a
및 b
예상대로 작동합니다 (즉, 자체 리디렉션없이).
참고 :이 솔루션은 스프레이 1.2 용입니다.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다