import os import uvicorn from fastapi import FastAPI, HTTPException from fastapi.responses import FileResponse, Response from loguru import logger from starlette.staticfiles import StaticFiles from starlette.types import Scope from .controller.domain import router as domain_router from .controller.report import router as report_router from .controller.status import router as status_router class SPAStaticFiles(StaticFiles): async def get_response(self, path: str, scope: Scope) -> Response: # 如果是前端路由,直接返回 index.html,否则直接访问的时候会404 if path in ("domain", "url"): return FileResponse(os.path.join(self.directory, "index.html")) return await super().get_response(path, scope) class WebApp: def __init__(self): self.app = FastAPI() @staticmethod async def start(): app = FastAPI() # 导入路由 app.include_router(status_router) app.include_router(report_router) app.include_router(domain_router) # 挂载前端文件 app.mount("/", SPAStaticFiles(directory="fe/dist", html=True), name="static") # TODO 先写死,后面从配置文件里取 cfg = uvicorn.Config(app, host="127.0.0.1", port=3000) server = uvicorn.Server(cfg) await server.serve()