f8b21af4be
10_Wiki/Topics 대규모 정리: - 오류 캡처/미완성 stub 문서 227개 제거 - 교차폴더 중복 43클러스터 병합 (63파일 → redirect) - 링크명 정규화: 깨진 링크 수정·redirect 직결·개념 매핑 ~2,400건 - 카테고리 MOC 6개 신규 생성 - Graph 섹션 미해결 related-keyword 링크 10,058건 제거 Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
260 lines
8.7 KiB
Markdown
260 lines
8.7 KiB
Markdown
---
|
|
id: wiki-2026-0508-router-implementation
|
|
title: Router Implementation
|
|
category: 10_Wiki/Topics
|
|
status: verified
|
|
canonical_id: self
|
|
aliases: [URL Router, HTTP Router, Trie Router]
|
|
duplicate_of: none
|
|
source_trust_level: A
|
|
confidence_score: 0.88
|
|
verification_status: applied
|
|
tags: [router, http, frontend, backend, data-structure]
|
|
raw_sources: []
|
|
last_reinforced: 2026-05-10
|
|
github_commit: pending
|
|
tech_stack:
|
|
language: TypeScript/Go
|
|
framework: Hono/Express/React Router
|
|
---
|
|
|
|
# Router Implementation
|
|
|
|
## 매 한 줄
|
|
> **"매 URL/path → handler 의 매칭을 최대한 효율적으로 dispatch"**. Web framework 의 가장 hot path 중 하나. 매 핵심 자료구조: linear array (Express, ~O(N)) → radix trie (httprouter, fastify) → static-first matcher (Hono RegExpRouter, 2023, O(1)). 매 frontend (React Router 7, TanStack Router) 도 같은 algorithm 을 client-side 에서 재현 + nested layout/loader 추가.
|
|
|
|
## 매 핵심
|
|
|
|
### 매 router 의 책임
|
|
- Path matching (static, param, wildcard, regex).
|
|
- Method dispatch (GET/POST/...).
|
|
- Middleware composition.
|
|
- Param extraction + type coercion (TanStack Router 의 zod 연동).
|
|
- 404 / 405 / OPTIONS 자동 처리.
|
|
|
|
### 매 자료구조 비교
|
|
- **Linear**: 매 Express — pattern 배열을 순회. O(N), N=route 수.
|
|
- **Radix trie**: 매 httprouter, fastify — prefix 공유로 O(L), L=path length. 매 backtracking 처리 복잡.
|
|
- **RegExp 합성**: 매 Hono RegExpRouter — 매 모든 route 를 single big regex 로 compile, O(1) match.
|
|
- **Static map + dynamic trie**: 매 hybrid — 매 static path 는 hashmap, 매 param path 는 trie.
|
|
|
|
### 매 응용
|
|
1. Hono RegExpRouter (Cloudflare Workers).
|
|
2. React Router 7 nested route + data loader.
|
|
3. TanStack Router file-based + typed search params.
|
|
4. Next.js App Router (file convention + nested layout).
|
|
|
|
## 💻 패턴
|
|
|
|
### 매 simplest: linear matcher (TS)
|
|
```typescript
|
|
type Handler = (req: Request, params: Record<string, string>) => Response | Promise<Response>;
|
|
type Route = { method: string; pattern: RegExp; keys: string[]; handler: Handler };
|
|
|
|
const routes: Route[] = [];
|
|
|
|
function add(method: string, path: string, handler: Handler) {
|
|
const keys: string[] = [];
|
|
const pattern = new RegExp(
|
|
'^' + path.replace(/:([a-zA-Z]+)/g, (_, k) => { keys.push(k); return '([^/]+)'; }) + '$',
|
|
);
|
|
routes.push({ method, pattern, keys, handler });
|
|
}
|
|
|
|
function dispatch(req: Request): Promise<Response> {
|
|
const url = new URL(req.url);
|
|
for (const r of routes) {
|
|
if (r.method !== req.method) continue;
|
|
const m = url.pathname.match(r.pattern);
|
|
if (!m) continue;
|
|
const params = Object.fromEntries(r.keys.map((k, i) => [k, m[i + 1]]));
|
|
return Promise.resolve(r.handler(req, params));
|
|
}
|
|
return Promise.resolve(new Response('Not Found', { status: 404 }));
|
|
}
|
|
```
|
|
|
|
### Radix trie node (TS)
|
|
```typescript
|
|
type Node = {
|
|
children: Map<string, Node>; // static segment
|
|
param?: { name: string; child: Node };
|
|
wildcard?: Node;
|
|
handlers: Map<string, Handler>;
|
|
};
|
|
|
|
function insert(root: Node, method: string, path: string, h: Handler) {
|
|
const segs = path.split('/').filter(Boolean);
|
|
let n = root;
|
|
for (const s of segs) {
|
|
if (s.startsWith(':')) {
|
|
n.param ??= { name: s.slice(1), child: emptyNode() };
|
|
n = n.param.child;
|
|
} else if (s === '*') {
|
|
n.wildcard ??= emptyNode();
|
|
n = n.wildcard;
|
|
} else {
|
|
let c = n.children.get(s);
|
|
if (!c) { c = emptyNode(); n.children.set(s, c); }
|
|
n = c;
|
|
}
|
|
}
|
|
n.handlers.set(method, h);
|
|
}
|
|
|
|
function emptyNode(): Node {
|
|
return { children: new Map(), handlers: new Map() };
|
|
}
|
|
```
|
|
|
|
### Trie lookup
|
|
```typescript
|
|
function find(root: Node, method: string, path: string)
|
|
: { handler: Handler; params: Record<string, string> } | null {
|
|
const segs = path.split('/').filter(Boolean);
|
|
const params: Record<string, string> = {};
|
|
let n = root;
|
|
for (const s of segs) {
|
|
const c = n.children.get(s);
|
|
if (c) { n = c; continue; }
|
|
if (n.param) { params[n.param.name] = s; n = n.param.child; continue; }
|
|
if (n.wildcard) { n = n.wildcard; break; }
|
|
return null;
|
|
}
|
|
const handler = n.handlers.get(method);
|
|
return handler ? { handler, params } : null;
|
|
}
|
|
```
|
|
|
|
### Hono-style RegExpRouter (compile-once)
|
|
```typescript
|
|
// 매 모든 route 를 단일 alternation regex 로 build
|
|
// /users/:id → ^\/users\/([^/]+)$ (group 1 = id, route index = 0)
|
|
// /posts/:id → ^\/posts\/([^/]+)$ (group 1 = id, route index = 1)
|
|
// merged: ^(?:\/users\/([^/]+)|\/posts\/([^/]+))$
|
|
|
|
class RegExpRouter {
|
|
private routes: { handler: Handler; keys: string[] }[] = [];
|
|
private re?: RegExp;
|
|
|
|
add(path: string, handler: Handler) {
|
|
const keys: string[] = [];
|
|
const pat = path.replace(/:([a-zA-Z]+)/g, (_, k) => { keys.push(k); return '([^/]+)'; });
|
|
this.routes.push({ handler, keys });
|
|
return pat;
|
|
}
|
|
|
|
build(patterns: string[]) {
|
|
this.re = new RegExp('^(?:' + patterns.map(p => `(${p})`).join('|') + ')$');
|
|
}
|
|
|
|
match(path: string) {
|
|
const m = this.re!.exec(path);
|
|
if (!m) return null;
|
|
// 매 어떤 alternative 가 hit 했는지 — group index 로 식별
|
|
const idx = m.findIndex((g, i) => i > 0 && g !== undefined && i % 2 === 1);
|
|
// (단순화 — 실제 Hono 는 grouping 인덱스를 정교하게 관리)
|
|
return { route: this.routes[idx / 2 | 0] };
|
|
}
|
|
}
|
|
```
|
|
|
|
### Go: net/http 1.22+ pattern matching
|
|
```go
|
|
// 매 Go 1.22 (2024) 부터 method + path pattern 내장
|
|
mux := http.NewServeMux()
|
|
mux.HandleFunc("GET /users/{id}", func(w http.ResponseWriter, r *http.Request) {
|
|
id := r.PathValue("id")
|
|
fmt.Fprintf(w, "user %s", id)
|
|
})
|
|
mux.HandleFunc("POST /users", createUser)
|
|
http.ListenAndServe(":8080", mux)
|
|
```
|
|
|
|
### React Router 7 (data router + loader)
|
|
```tsx
|
|
import { createBrowserRouter, RouterProvider } from 'react-router';
|
|
|
|
const router = createBrowserRouter([
|
|
{
|
|
path: '/',
|
|
Component: RootLayout,
|
|
children: [
|
|
{ index: true, Component: Home },
|
|
{
|
|
path: 'users/:id',
|
|
loader: async ({ params }) => fetch(`/api/users/${params.id}`).then(r => r.json()),
|
|
Component: UserPage,
|
|
},
|
|
],
|
|
},
|
|
]);
|
|
|
|
export default () => <RouterProvider router={router} />;
|
|
```
|
|
|
|
### TanStack Router (typed)
|
|
```tsx
|
|
import { createRoute, createRouter } from '@tanstack/react-router';
|
|
import { z } from 'zod';
|
|
|
|
const userRoute = createRoute({
|
|
getParentRoute: () => rootRoute,
|
|
path: '/users/$id',
|
|
validateSearch: z.object({ tab: z.enum(['profile', 'orders']).default('profile') }),
|
|
loader: ({ params }) => fetch(`/api/users/${params.id}`).then(r => r.json()),
|
|
component: UserPage,
|
|
});
|
|
// 매 params + search 모두 type-safe
|
|
```
|
|
|
|
### Trailing-slash + 405 normalization
|
|
```typescript
|
|
function normalize(path: string) {
|
|
if (path.length > 1 && path.endsWith('/')) return path.slice(0, -1);
|
|
return path;
|
|
}
|
|
// 405: path 는 hit 하나 method 가 없을 때
|
|
// → Allow header 에 등록된 method 들을 응답
|
|
```
|
|
|
|
## 매 결정 기준
|
|
| 상황 | Approach |
|
|
|---|---|
|
|
| Edge runtime (Workers, Deno) | Hono RegExpRouter — cold start O(1) |
|
|
| Node monolith | Fastify (radix trie) |
|
|
| Go service | net/http 1.22 또는 chi |
|
|
| Static-heavy (mostly fixed paths) | Hashmap + fallback trie |
|
|
| SPA | React Router 7 또는 TanStack Router |
|
|
| Type-safe params + search | TanStack Router |
|
|
| File convention | Next.js App / Remix / TanStack Start |
|
|
|
|
**기본값**: 매 backend — radix trie (Hono/Fastify). 매 frontend — TanStack Router (typed) 또는 React Router 7.
|
|
|
|
## 🔗 Graph
|
|
- 부모: [[HTTP]] · [[Trie]]
|
|
- 응용: [[Hono]] · [[Fastify]] · [[TanStack Router]]
|
|
- Adjacent: [[Middleware]] · [[Reverse Proxy]] · [[Service Mesh]]
|
|
|
|
## 🤖 LLM 활용
|
|
**언제**: 매 router algorithm 학습, 매 small framework 작성, 매 path-matching DSL 설계.
|
|
**언제 X**: 매 production framework 직접 구현 — 매 edge case (UTF-8, percent-decode, security) 가 매 무궁무진. Hono/Fastify/React Router 사용.
|
|
|
|
## ❌ 안티패턴
|
|
- **Linear scan at scale**: 매 1000+ route — Express 의 약점.
|
|
- **Regex DOS**: 매 사용자 input 을 path pattern 으로 — ReDoS.
|
|
- **Param shadowing**: 매 `/:id` vs `/users` 우선순위 모호 — static 우선.
|
|
- **No 405 / Allow**: 매 매칭은 되나 method 없을 때 404 (incorrect — should be 405).
|
|
- **Router 가 business logic 보유**: 매 router 는 dispatch 만, handler 가 logic.
|
|
- **Untyped params**: 매 frontend 에서 매 `params.id` 가 `any` — TanStack 의 typed router 사용.
|
|
|
|
## 🧪 검증 / 중복
|
|
- Verified: Hono RegExpRouter benchmark (yusukebe.com 2023), httprouter (julienschmidt 2014), Go 1.22 release notes (2024), React Router v7 docs (2025).
|
|
- 신뢰도 A.
|
|
|
|
## 🕓 Changelog
|
|
| 날짜 | 변경 |
|
|
|---|---|
|
|
| 2026-05-08 | Phase 1 |
|
|
| 2026-05-10 | Manual cleanup — linear/trie/regexp + Go 1.22 + React Router 7 + TanStack |
|