"""HTTP 路由 - 基于 oss/shared/router.py 的 BaseRouter""" import json from typing import Callable from oss.shared.router import BaseRouter, BaseRoute, match_path, extract_path_params from .server import Request, Response class HttpRouter(BaseRouter): """HTTP 路由""" def add(self, method: str, path: str, handler: Callable): self.routes.append(BaseRoute(method, path, handler)) def handle(self, request: Request) -> Response: """匹配路由并执行处理器""" for route in self.routes: if route.method == request.method and match_path(route.path, request.path): params = extract_path_params(route.path, request.path) try: result = route.handler(request, **params) if isinstance(result, Response): return result return Response( status=200, body=json.dumps(result) if not isinstance(result, str) else result, headers={"Content-Type": "application/json"} ) except Exception as e: return Response( status=500, body=json.dumps({"error": "Internal Server Error", "message": str(e)}), headers={"Content-Type": "application/json"} ) # 404 - 无匹配路由 return Response( status=404, body=json.dumps({"error": "Not Found", "message": f"路由未找到: {request.method} {request.path}"}), headers={"Content-Type": "application/json"} )