File size: 3,589 Bytes
1560e5b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 | 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("""
<!DOCTYPE html>
<html>
<head>
<title>OpenClaw Proxy</title>
<style>
body { font-family: sans-serif; padding: 20px; }
.nav { margin-bottom: 20px; }
.nav a { margin-right: 10px; padding: 10px; background: #007bff; color: white; text-decoration: none; border-radius: 5px; }
iframe { width: 100%; height: 90vh; border: 1px solid #ccc; }
</style>
</head>
<body>
<div class="nav">
<a href="/openclaw/">OpenClaw</a>
<a href="/status">Status</a>
</div>
<h2>OpenClaw Gateway Proxy</h2>
<p>Click above to access services</p>
</body>
</html>
""")
@app.get("/openclaw/")
async def openclaw_redirect():
# 重写到 OpenClaw Canvas 页面
return HTMLResponse("""
<!DOCTYPE html>
<html>
<head>
<title>OpenClaw</title>
<style>body { margin: 0; }</style>
</head>
<body>
<iframe src="/__openclaw__/canvas/" style="width:100%; height:100vh; border:none;"></iframe>
</body>
</html>
""")
# 代理 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) |