I just thought of an interesting API design for server routing from a URL:
when Route.fromUrl url is
Get ["users", username] -> # e.g. /users/rtfeldman
Get ["users", username, "profile"] -> # e.g. /users/foo/profile
Get ["search"] if Dict.contains params "q" -> # e.g. /search?q=blah
Post ["register"] -> # has to be exactly /register
then if you need additional parsing (like for Get ["users", userId]
where userId
is an integer) you'd do that after the initial match, e.g. running Num.fromStr
on them as necessary
I assume that for checking such guards (is number, is number within the expected range, etc), you would create a private helper function and use the same if Dict.contains .....
strategy with that private function. This way, you don't have to "step into" the match and then have no way to step back to check if a later route would match. Would that work?
Sounds reasonable, but I would be concerned of perf. Routers get hit a lot. Even the tiniest of perf gains can help. I wonder if routers in other languages do something special to keep perf really high here. Just in general questioning if a full flat match over a list of strings will be performant. Might be fine, just questioning.
it's a good question...I wonder if a future compiler optimization could be a good idea for when
on a list of strings
Str.split path "/"
should be fast and the substrings should all be slices, so no allocations aside from the 1 for the list itself
and then "GET"
to Get
should be fast too
so I think the only question would be how quickly the List Str
can be matched up with a particular when
branch like this, and that's what I think maybe a compiler optimization could improve in the future
Very fair. I guess everything should be slices, so that should be pretty decent.
*slices or clones of parts of small strings
Honestly, the dictionary lookup may be likely to be the slowest part
for the query?
that could also just be a List
Yeah, probably should be a VecMap
I like how simple that router is.
Last updated: Jul 06 2025 at 12:14 UTC