Is there something like `routes()` which chooses t...
# http4k
d
Is there something like
routes()
which chooses the first matching handler? Or is it the wrong thing to do anyway? For the context I’m profiling a simple http4k app (with get/set endpoints) and can see that
OrRouter
takes about 5% of time. Wondering if there is an easy way to make it ~0% 😅
d
Yes - it should select the first one that matches or eventually return a 404
@Dmitry Kandalov it does iterate over the entire lot and then select the best match
but that could be tightened up
current implementation is
Copy code
override fun match(request: Request): RouterMatch {
        val matches = list.map { next -> next.match(request) }
        val result = matches.minOrNull() ?: Unmatched(description)
        return result.aggregatedBy(description, matches)
    }
we could iterate over the list and if it finds a total match then shortcut the iteration
d
yes, I guess something like this 🤔 (but more optimised)
Copy code
override fun match(request: Request) =
        list.asSequence()
            .map { next -> next.match(request) }
            .filterIsInstance<MatchingHandler>()
            .firstOrNull() ?: Unmatched(description)
d
the problem is that it still needs all of the matches for the aggregate by
j
if you sort the list to start with, maybe you can pick the first one?
d
Btw, just discovered that writing custom
FirstMatchRouter
means I need to copy-paste
RouterBasedHttpHandler
because it’s internal in http4k-core.