Search code examples
ktor

How to list configured routes in Ktor


I am setting up a project with multiple modules that contain different versions of api.

To verify correct route configuration I would like to print configured routes to application log like it is done in spring framework.

Is it possible and what should I use for that?


Solution

  • You can do it by recursively traversing routes starting from the root all the way down the tree and filtering in only ones with the HTTP method selector. This solution is described here.

    fun Application.module() {
        // routing configuration goes here
    
        val root = feature(Routing)
        val allRoutes = allRoutes(root)
        val allRoutesWithMethod = allRoutes.filter { it.selector is HttpMethodRouteSelector }
        allRoutesWithMethod.forEach {
            println("route: $it")
        }
    }
    
    fun allRoutes(root: Route): List<Route> {
        return listOf(root) + root.children.flatMap { allRoutes(it) }
    }
    

    Please note that the code above must be placed after the routing configuration.