Ktor: List of all routes

Created on 29 Jul 2019  路  2Comments  路  Source: ktorio/ktor

https://github.com/ktorio/ktor/issues/788Subsystem
Server

Is your feature request related to a problem? Please describe.
No

Describe the solution you'd like
Things like spring actuator are able to list all the endpoints in the current system. Something like this for ktor would be very helpful.

Motivation to include to ktor
A very common usage so makes sense to build directly into ktor.

feature

Most helpful comment

I was interested logging all computed routes on service startup, in a cheap way, so did a small investigation.

You can traverse the tree of Routes, picking out leaves by filtering on a property, such as the route having a method selector. Assuming there can't be cycles:

fun Application.ktorMain() {
    // set up omitted
    val root = feature(Routing)
    val allRoutes = allRoutes(root)
    val allRoutesWithMethod = allRoutes.filter { it.selector is HttpMethodRouteSelector }
    allRoutesWithMethod.forEach {
        logger.info("route: $it")
    }
}

fun allRoutes(root: Route): List<Route> {
    return listOf(root) + root.children.flatMap { allRoutes(it) }
}

Example output:

22:41:42.148 [main] INFO  Service - route: /(authenticate adoptanimals-session-cookie)/shelter/{shelterVisualId}/(method:GET)
22:41:42.148 [main] INFO  Service - route: /private/healthcheck/(method:GET)

I've no doubt there'll be a better way built in eventually, but this did what we needed for now.

All 2 comments

I was interested logging all computed routes on service startup, in a cheap way, so did a small investigation.

You can traverse the tree of Routes, picking out leaves by filtering on a property, such as the route having a method selector. Assuming there can't be cycles:

fun Application.ktorMain() {
    // set up omitted
    val root = feature(Routing)
    val allRoutes = allRoutes(root)
    val allRoutesWithMethod = allRoutes.filter { it.selector is HttpMethodRouteSelector }
    allRoutesWithMethod.forEach {
        logger.info("route: $it")
    }
}

fun allRoutes(root: Route): List<Route> {
    return listOf(root) + root.children.flatMap { allRoutes(it) }
}

Example output:

22:41:42.148 [main] INFO  Service - route: /(authenticate adoptanimals-session-cookie)/shelter/{shelterVisualId}/(method:GET)
22:41:42.148 [main] INFO  Service - route: /private/healthcheck/(method:GET)

I've no doubt there'll be a better way built in eventually, but this did what we needed for now.

Please check the following ticket on YouTrack for follow-ups to this issue. GitHub issues will be closed in the coming weeks.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

KennethanCeyer picture KennethanCeyer  路  4Comments

diaodou picture diaodou  路  3Comments

wellingtoncosta picture wellingtoncosta  路  3Comments

scorsi picture scorsi  路  4Comments

ManifoldFR picture ManifoldFR  路  4Comments