Mini Router with 404 and 405
Medium · Routing
Write handle(routes, method, url), a tiny router. routes is a list of { method, path, status, body }, where path may contain :params.
- Ignore the query string (everything from ?).
- A path matches when it has the same number of / segments and every segment is equal, or is a :param with a non-empty value. Params are returned as raw strings (no decoding).
- Routes are checked in order and the first route with a matching path AND method wins: return { status, body, params }.
- If some routes match the path but none match the method, return { status: 405, body: "Method Not Allowed", allow } where allow lists those routes' methods in route order, without duplicates (real servers send this as the Allow header).
- If no route matches the path, return { status: 404, body: "Not Found" }.
Next: CORS Headers