opc / proxy.py
bill322's picture
Create proxy.py
1560e5b verified
Raw History Blame Contribute Delete
3.59 kB
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)