[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -4,113 +4,257 @@ title: Router Implementation
|
||||
category: 10_Wiki/Topics
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [P-REINFORCE-WIKI-WEB-ROUTERS, 라우터, Routers, 요청 분기, Entry Point]
|
||||
aliases: [URL Router, HTTP Router, Trie Router]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 1.0
|
||||
tags: [Architecture, Routing, Entry_Point, API_Gateway, Flow_Analysis]
|
||||
raw_sources: [Datacollector_Export_2026-05-02]
|
||||
last_reinforced: 2026-05-02
|
||||
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: unspecified
|
||||
framework: unspecified
|
||||
language: TypeScript/Go
|
||||
framework: Hono/Express/React Router
|
||||
---
|
||||
|
||||
# [[라우터의 역할과 구현 원칙 (Router Implementation)]]
|
||||
# Router Implementation
|
||||
|
||||
## 1. 개요
|
||||
라우터(Routers)는 시스템 내에서 클라이언트의 요청이나 이벤트를 적절한 목적지나 처리 로직으로 전달하는 관문 역할을 수행한다. 코드베이스 분석 관점에서 라우터는 시스템의 전체 기능과 데이터 흐름을 파악하기 위한 가장 중요한 **진입점(Entry Point)**이다.
|
||||
## 매 한 줄
|
||||
> **"매 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 추가.
|
||||
|
||||
## 2. 아키텍처적 역할
|
||||
- **시스템 진입점**: 외부 요청이 비즈니스 로직으로 변환되는 첫 번째 지점.
|
||||
- **요청 분기 및 오케스트레이션**: URL 경로, HTTP 메서드, 헤더 정보를 기반으로 적절한 핸들러나 서비스로 요청을 분배.
|
||||
- **관심사 분리 (SoC)**: 라우팅 로직을 비즈니스 로직(Service Layer)과 분리하여 코드의 가독성과 유지보수성 향상.
|
||||
- **보안 및 필터링**: 라우터 계층에서 인증(Auth), 인가, 속도 제한(Rate Limiting) 등 공통 기능을 선제적으로 처리.
|
||||
## 매 핵심
|
||||
|
||||
## 3. 라우팅 패턴의 진화
|
||||
- **정적 라우팅 (Static Routing)**: 라우트 경로와 핸들러를 코드에 명시적으로 매핑.
|
||||
- **설정 기반 라우팅 (Configuration-based)**: JSON이나 특정 설정 파일을 통해 라우팅 규칙 관리.
|
||||
- **파일 기반 라우팅 (File-based)**: 디렉토리 구조가 곧 경로가 되는 현대적 패러다임 (예: Next.js).
|
||||
- **이벤트 라우팅**: 메시지 브로커가 이벤트를 적절한 소비자에게 전달하는 비동기 라우팅.
|
||||
### 매 router 의 책임
|
||||
- Path matching (static, param, wildcard, regex).
|
||||
- Method dispatch (GET/POST/...).
|
||||
- Middleware composition.
|
||||
- Param extraction + type coercion (TanStack Router 의 zod 연동).
|
||||
- 404 / 405 / OPTIONS 자동 처리.
|
||||
|
||||
## 4. 코드베이스 탐색 전략
|
||||
- **하향식(Top-down) 분석**: 라우터 파일(예: `routes/`, `controllers/`)을 먼저 찾아 시스템이 제공하는 API 목록을 파악하고, 각 엔드포인트의 호출 스택을 따라 내려가며 기능을 해독.
|
||||
- **경계 식별**: API 게이트웨이나 메인 라우터를 통해 시스템의 외부 경계와 내부 서비스 간의 연결 구조를 시각화.
|
||||
### 매 자료구조 비교
|
||||
- **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.
|
||||
|
||||
## 5. 지식 연결 (Related)
|
||||
- [[File_based_Routing]]: 현대적 웹 프레임워크의 주류 라우팅 방식.
|
||||
- [[API_Gateway_Pattern]]: 분산 시스템에서의 중앙 집중형 라우팅 전략.
|
||||
- [[Codebase_Onboarding_Guide]]: 라우터를 기점으로 시스템을 빠르게 파악하는 방법.
|
||||
### 매 응용
|
||||
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).
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
- **정보 상태**: 검증 완료 (Verified)
|
||||
- **출처 신뢰도**: A
|
||||
- **검토 이유**: 시스템의 구조적 파악과 기능 추적의 시작점이 되는 라우터의 핵심 개념 정립.
|
||||
## 💻 패턴
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
### 매 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 };
|
||||
|
||||
> *(TODO: 한 문장으로 핵심 통찰을 작성. "X는 Y 조건에서 Z 효과를 낸다" 구조 권장.)*
|
||||
const routes: Route[] = [];
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
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 });
|
||||
}
|
||||
|
||||
**추출된 패턴:**
|
||||
> *(TODO)*
|
||||
|
||||
**세부 내용:**
|
||||
- *(TODO)*
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
|
||||
- **과거 데이터와의 충돌:** 없음
|
||||
- **정책 변화:** 없음
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
|
||||
- **Parent:** [[10_Wiki/Topics]]
|
||||
- **Related:** *(TODO: 최소 2개)*
|
||||
- **Opposite / Trade-off:** *(TODO)*
|
||||
- **Raw Source:** 직접 입력
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
|
||||
## 💻 코드 패턴 (Code Patterns)
|
||||
|
||||
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
|
||||
|
||||
```text
|
||||
# TODO
|
||||
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 }));
|
||||
}
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### Radix trie node (TS)
|
||||
```typescript
|
||||
type Node = {
|
||||
children: Map<string, Node>; // static segment
|
||||
param?: { name: string; child: Node };
|
||||
wildcard?: Node;
|
||||
handlers: Map<string, Handler>;
|
||||
};
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
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);
|
||||
}
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
function emptyNode(): Node {
|
||||
return { children: new Map(), handlers: new Map() };
|
||||
}
|
||||
```
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
### 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;
|
||||
}
|
||||
```
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
### 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\/([^/]+))$
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
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]] · [[Web Framework]] · [[Trie]]
|
||||
- 변형: [[Radix Trie Router]] · [[RegExp Router]] · [[File-based Router]]
|
||||
- 응용: [[Hono]] · [[Fastify]] · [[React Router]] · [[TanStack Router]] · [[Next.js App 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 |
|
||||
|
||||
Reference in New Issue
Block a user