Initial upload: API Mock CLI v0.1.0
Some checks failed
CI / test (3.11) (push) Has been cancelled
CI / test (3.12) (push) Has been cancelled
CI / test (3.9) (push) Has been cancelled
CI / lint (push) Has been cancelled
CI / type-check (push) Has been cancelled
CI / build (push) Has been cancelled
CI / test (3.10) (push) Has been cancelled

This commit is contained in:
2026-01-29 13:53:44 +00:00
parent bdf330ef19
commit e8c6a1a650

38
src/core/router.py Normal file
View File

@@ -0,0 +1,38 @@
import re
from typing import Optional, Dict, Tuple, List, Any
from src.models.endpoint import Endpoint
class Router:
def __init__(self):
self.routes: List[Tuple[re.Pattern, Endpoint, Dict[str, str]]] = []
self._compile_regex()
def _path_to_regex(self, path: str) -> Tuple[str, Dict[str, str]]:
param_names = {}
regex_path = re.sub(r"\{(\w+)\}", lambda m: param_names.__setitem__(m.group(1), m.group(0)) or "(?P<" + m.group(1) + ">[^/]+)", path)
regex_path = f"^{regex_path}$"
return regex_path, param_names
def _compile_regex(self):
pass
def add_route(self, endpoint: Endpoint):
pattern, param_names = self._path_to_regex(endpoint.path)
compiled = re.compile(pattern)
self.routes.append((compiled, endpoint, param_names))
def match(self, path: str, method: str) -> Optional[Tuple[Endpoint, Dict[str, str]]]:
for compiled_pattern, endpoint, param_names in self.routes:
if endpoint.method.upper() != method.upper():
continue
match = compiled_pattern.match(path)
if match:
return endpoint, match.groupdict()
return None
def get_all_routes(self) -> List[Endpoint]:
return [endpoint for _, endpoint, _ in self.routes]
def clear(self):
self.routes.clear()