Skip to content

Commit

Permalink
KTOR-2427 fix trailing slash toString (#2419)
Browse files Browse the repository at this point in the history
  • Loading branch information
rsinukov authored Apr 29, 2021
1 parent 6763a73 commit e61f55f
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 7 deletions.
16 changes: 9 additions & 7 deletions ktor-server/ktor-server-core/jvm/src/io/ktor/routing/Route.kt
Original file line number Diff line number Diff line change
Expand Up @@ -110,14 +110,16 @@ public open class Route(
}
}

override fun toString(): String = when {
parent == null -> "/$selector"
parent.parent == null -> parent.toString().let { parentText ->
when {
parentText.endsWith('/') -> "$parentText$selector"
else -> "$parentText/$selector"
override fun toString(): String {
return when (val parentRoute = parent?.toString()) {
null -> when (selector) {
is TrailingSlashRouteSelector -> "/"
else -> "/$selector"
}
else -> when (selector) {
is TrailingSlashRouteSelector -> if (parentRoute.endsWith('/')) parentRoute else "$parentRoute/"
else -> if (parentRoute.endsWith('/')) "$parentRoute$selector" else "$parentRoute/$selector"
}
}
else -> "$parent/$selector"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/*
* Copyright 2014-2021 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
*/

package io.ktor.tests.routing

import io.ktor.routing.*
import kotlin.test.*

class RouteTest {

@Test
fun testToStringSimple() {
val root = Route(parent = null, selector = PathSegmentConstantRouteSelector("root"))
val simpleChild = Route(parent = root, selector = PathSegmentConstantRouteSelector("simpleChild"))
val simpleGrandChild =
Route(parent = simpleChild, selector = PathSegmentConstantRouteSelector("simpleGrandChild"))

val slashChild = Route(parent = root, selector = TrailingSlashRouteSelector)
val slashGrandChild = Route(parent = slashChild, selector = TrailingSlashRouteSelector)
val simpleChildInSlash = Route(parent = slashGrandChild, PathSegmentConstantRouteSelector("simpleChildInSlash"))
val slashChildInSimpleChild = Route(parent = simpleChildInSlash, TrailingSlashRouteSelector)

assertEquals("/root", root.toString())
assertEquals("/root/simpleChild", simpleChild.toString())
assertEquals("/root/simpleChild/simpleGrandChild", simpleGrandChild.toString())
assertEquals("/root/", slashChild.toString())
assertEquals("/root/", slashGrandChild.toString())
assertEquals("/root/simpleChildInSlash", simpleChildInSlash.toString())
assertEquals("/root/simpleChildInSlash/", slashChildInSimpleChild.toString())
}
}

0 comments on commit e61f55f

Please sign in to comment.