💻 Dev

🛠️ 처음부터 만드는 Router — Express-style 경로 매칭 엔진 20줄 구현

`/users/:id` → 어떻게 `{ id: "42" }`가 되는 걸까?
Express, Hono, Fastify 모두 내부적으로 경로 패턴을 정규식으로 변환한다.
핵심 로직은 놀랍도록 단순하다.

구현


```js
class Router {
#routes = [];
#add(method, path, fn) {
const keys = [];
const pattern = path.replace(/:([\w]+)/g, (_, k) =>
(keys.push(k), '([^/]+)'));
this.#routes.push({
method, re: new RegExp(`^${pattern}$`), keys, fn
});
}
get(p, fn) { this.#add('GET', p, fn); return this; }
post(p, fn) { this.#add('POST', p, fn); return this; }
match(method, url) {
for (const r of this.#routes) {
if (r.method !== method) continue;
const m = url.match(r.re);
if (!m) continue;
const params = Object.fromEntries(
r.keys.map((k, i) => [k, m[i + 1]]));
return { handler: r.fn, params };
}
return null;
}
}
```

사용


```js
const app = new Router();
app.get('/users/:id', (p) => `User ${p.id}`)
.get('/posts/:year/:slug', (p) => `${p.year}/${p.slug}`);
const r1 = app.match('GET', '/users/42');
r1.handler(r1.params); // "User 42"
const r2 = app.match('GET', '/posts/2026/hello-world');
r2.handler(r2.params); // "2026/hello-world"
```

핵심 원리


`:id` → `([^/]+)` 변환이 전부다.
매칭 시 캡처 그룹 순서 = 파라미터 키 순서.
Express의 `path-to-regexp`도 동일한 원리에
와일드카드(`*`), 옵셔널(`?`), 정규식 그룹을 추가한 것.
> 프레임워크의 라우팅 마법은 정규식 한 줄이었다.
💬 0
👁 0 views

Comments (0)

💬

No comments yet.

Be the first to comment!