diff --git a/ktor-server/ktor-server-core/jvm/src/io/ktor/routing/Route.kt b/ktor-server/ktor-server-core/jvm/src/io/ktor/routing/Route.kt index 9c3bbd8f5df..e0b8f3ebef3 100644 --- a/ktor-server/ktor-server-core/jvm/src/io/ktor/routing/Route.kt +++ b/ktor-server/ktor-server-core/jvm/src/io/ktor/routing/Route.kt @@ -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" } } diff --git a/ktor-server/ktor-server-core/jvm/test/io/ktor/tests/routing/RouteTest.kt b/ktor-server/ktor-server-core/jvm/test/io/ktor/tests/routing/RouteTest.kt new file mode 100644 index 00000000000..1c74276fb5a --- /dev/null +++ b/ktor-server/ktor-server-core/jvm/test/io/ktor/tests/routing/RouteTest.kt @@ -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()) + } +}