Skip to content

Commit

Permalink
Merge pull request #2728 from rossabaker/issue-2726
Browse files Browse the repository at this point in the history
Preserve request caret in withPathInfo
  • Loading branch information
rossabaker committed Jul 23, 2019
2 parents 14fcda9 + c473d92 commit 91bdba6
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 12 deletions.
10 changes: 6 additions & 4 deletions core/src/main/scala/org/http4s/Message.scala
Expand Up @@ -294,13 +294,15 @@ sealed abstract case class Request[F[_]](
attributes = attributes
)

lazy val (scriptName, pathInfo) = {
val caret = attributes.lookup(Request.Keys.PathInfoCaret).getOrElse(0)
lazy val (scriptName, pathInfo) =
uri.path.splitAt(caret)
}

private def caret =
attributes.lookup(Request.Keys.PathInfoCaret).getOrElse(0)

def withPathInfo(pi: String): Self =
withUri(uri.withPath(scriptName + pi))
// Don't use withUri, which clears the caret
copy(uri = uri.withPath(scriptName + pi))

def pathTranslated: Option[File] = attributes.lookup(Keys.PathTranslated)

Expand Down
Expand Up @@ -15,22 +15,18 @@ import cats.implicits._
object AutoSlash {
def apply[F[_], G[_], B](http: Kleisli[F, Request[G], B])(
implicit F: MonoidK[F],
G: Functor[G]): Kleisli[F, Request[G], B] =
G: Functor[G]): Kleisli[F, Request[G], B] = {
val _ = G // for binary compatibility in 0.20, remove on master
Kleisli { req =>
http(req) <+> {
val pathInfo = req.pathInfo
val scriptName = req.scriptName

if (pathInfo.isEmpty || pathInfo.charAt(pathInfo.length - 1) != '/') {
F.empty
} else if (scriptName.isEmpty) {
// Request has not been translated already
http.apply(req.withPathInfo(pathInfo.substring(0, pathInfo.length - 1)))
} else {
// Request has been translated at least once, redo the translation
val translated = TranslateUri(scriptName)(http)
translated.apply(req.withPathInfo(pathInfo.substring(0, pathInfo.length - 1)))
http.apply(req.withPathInfo(pathInfo.substring(0, pathInfo.length - 1)))
}
}
}
}
}
10 changes: 10 additions & 0 deletions tests/src/test/scala/org/http4s/MessageSpec.scala
Expand Up @@ -96,6 +96,16 @@ class MessageSpec extends Http4sSpec {
originalReq.pathInfo mustEqual updatedReq.pathInfo
originalReq.scriptName mustEqual updatedReq.scriptName
}

"preserve caret in withPathInfo" in {
val originalReq = Request(
uri = Uri(path = "/foo/bar"),
attributes = Vault.empty.insert(Request.Keys.PathInfoCaret, 4))
val updatedReq = originalReq.withPathInfo("/quux")

updatedReq.scriptName mustEqual "/foo"
updatedReq.pathInfo mustEqual "/quux"
}
}

"toString" should {
Expand Down

0 comments on commit 91bdba6

Please sign in to comment.