import uvicorn import re from fastapi import FastAPI, Request from fastapi.responses import HTMLResponse, Response from starlette.middleware.base import BaseHTTPMiddleware # 匯入原本的三個檔案 from sprite_tool_fullstack import app as grid_app from sprite_webtool import app as picker_app from shiny_maker import app as shiny_app app = FastAPI(title="Game Dev Suite") # --- 定義導覽列 HTML --- NAVBAR_HTML = """ """ class NavbarMiddleware(BaseHTTPMiddleware): async def dispatch(self, request: Request, call_next): response = await call_next(request) # 排除首頁,避免重複注入 if request.url.path == "/": return response # 針對所有子工具的 HTML 回傳進行注入 if "text/html" in response.headers.get("content-type", ""): body = b"" async for chunk in response.body_iterator: body += chunk html_content = body.decode("utf-8") # 使用正則表達式匹配
標籤,不論它有沒有帶 class 或其他屬性 # 這會匹配 並在其後方插入 Navbar new_content = re.sub(r'(]*>)', r'\1' + NAVBAR_HTML, html_content, flags=re.IGNORECASE) return HTMLResponse(content=new_content, status_code=response.status_code) return response app.add_middleware(NavbarMiddleware) # --- 掛載子應用程式 --- app.mount("/grid", grid_app) app.mount("/picker", picker_app) app.mount("/shiny", shiny_app) # 首頁入口 @app.get("/", response_class=HTMLResponse) async def index(): return f""" {NAVBAR_HTML}請從上方導覽列選擇要使用的工具