https://kotlinlang.org logo
#http4k
Title
# http4k
d

Dmitry Kandalov

03/01/2024, 11:24 AM
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

dave

03/01/2024, 11:26 AM
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

Dmitry Kandalov

03/01/2024, 11:31 AM
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

dave

03/01/2024, 11:32 AM
the problem is that it still needs all of the matches for the aggregate by
j

James Richardson

03/01/2024, 2:36 PM
if you sort the list to start with, maybe you can pick the first one?
d

Dmitry Kandalov

03/12/2024, 5:21 PM
Btw, just discovered that writing custom
FirstMatchRouter
means I need to copy-paste
RouterBasedHttpHandler
because it’s internal in http4k-core.