import asyncio import websockets import httpx from fastapi import FastAPI, Request, WebSocket from fastapi.responses import HTMLResponse, StreamingResponse import uvicorn app = FastAPI() # OpenClaw 内部端口 OPENCLAW_PORT = 7861 @app.get("/") async def root(): # 返回简单的切换页面 return HTMLResponse(""" OpenClaw Proxy

OpenClaw Gateway Proxy

Click above to access services

""") @app.get("/openclaw/") async def openclaw_redirect(): # 重写到 OpenClaw Canvas 页面 return HTMLResponse(""" OpenClaw """) # 代理 HTTP 请求到 OpenClaw @app.api_route("/{path:path}", methods=["GET", "POST", "PUT", "DELETE", "OPTIONS", "HEAD", "PATCH"]) async def proxy_http(request: Request, path: str): target_url = f"http://127.0.0.1:{OPENCLAW_PORT}/{path}" # 处理查询参数 if request.query_params: target_url += f"?{request.query_params}" # 转发 headers(排除 host) headers = dict(request.headers) headers.pop("host", None) # 读取 body body = await request.body() async with httpx.AsyncClient() as client: try: response = await client.request( method=request.method, url=target_url, headers=headers, content=body, timeout=30.0 ) return StreamingResponse( content=response.aiter_raw(), status_code=response.status_code, headers=dict(response.headers) ) except Exception as e: return HTMLResponse(f"Error connecting to OpenClaw: {e}", status_code=502) # 代理 WebSocket 到 OpenClaw @app.websocket("/ws") @app.websocket("/{path:path}") async def proxy_ws(websocket: WebSocket, path: str = ""): await websocket.accept() target_ws = f"ws://127.0.0.1:{OPENCLAW_PORT}/{path}" try: async with websockets.connect(target_ws) as ws: # 双向转发 async def client_to_server(): while True: data = await websocket.receive_text() await ws.send(data) async def server_to_client(): while True: data = await ws.recv() await websocket.send_text(data) await asyncio.gather(client_to_server(), server_to_client()) except Exception as e: print(f"WebSocket error: {e}") finally: await websocket.close() @app.get("/status") async def status(): return {"status": "ok", "openclaw_port": OPENCLAW_PORT} if __name__ == "__main__": uvicorn.run(app, host="0.0.0.0", port=7860)