Backend

A router in 20 lines

Each path gets its own handler, and /posts/:slug hands the slug over as a parameter. None of the 20 lines is a regular expression.

A terminal with two curl requests: one to /posts/hello answers 200, one to /nope answers 404.
Two requests against the router at the end of this chapter.

Last chapter ended with a server that answers every request with the same text. That was fine for one page and useless for two. This chapter gives each path its own handler, and /posts/:slug hands the slug over as a parameter. The whole router is 20 lines, and none of them is a regular expression.

A diagram: socket to parse to match to handler, and the response written back to the socket.
Where the router sits between the parsed request and the handler.

Splitting the path

A pattern and a path are both split at /. They match when they have the same number of parts and every part is equal, except parts that start with :. Those become parameters.

function compare(parts: string[], path: string[]) {
  if (parts.length !== path.length) return null;
  const params: Record<string, string> = {};
  for (const [i, part] of parts.entries()) {
    if (part.startsWith(':')) params[part.slice(1)] = path[i]; // [!code highlight]
    else if (part !== path[i]) return null;
  }
  return params;
}

Registering and matching

export function route(method: string, pattern: string, handler: Handler) {
  routes.push({ method, parts: pattern.split('/'), handler });
}

export function match(req: Request) {
  const path = new URL(req.url).pathname.split('/');
  for (const r of routes) {
    const params = r.method === req.method && compare(r.parts, path);
    if (params) return r.handler(req, params);
  }
  return new Response('Not found', { status: 404 });
}

Wiring it into the server

-const handle = () => new Response('Hello');
+import { match, route } from './router.ts';
+route('GET', '/posts/:slug', (req, { slug }) => new Response(`You asked for: ${slug}`));
+const handle = match;

Is it fast enough?

Routes are compared in order, so the cost grows with their number. With twelve routes it does not show: the router costs 6 % against no router at all.

A bar chart: 41,380 requests a second without a router, 38,905 with it, 31,270 with the router and logging.
autocannon, 30 seconds, 100 connections, on the mini PC.
Setup Requests a second p99 latency
No router 41,380 4.1 ms
Router 38,905 4.4 ms
Router and logging 31,270 5.6 ms

The code as it stands after this chapter, if you want to run it:

Comments

Buy Logbuch