BG5 commited on
Commit
da21cc3
·
verified ·
1 Parent(s): 408cc4a

Update fun.py

Browse files
Files changed (1) hide show
  1. fun.py +27 -16
fun.py CHANGED
@@ -1,22 +1,24 @@
1
- from fastapi import FastAPI, Request, Response, status, WebSocket, WebSocketDisconnect
2
  import httpx
3
  import uvicorn
4
  import asyncio
5
  import websockets
 
6
 
7
  app = FastAPI()
8
 
9
- TARGET_BASE = "http://127.0.0.1:9222" # 目标服务器(Chrome DevTools
10
- TARGET_WS_BASE = "ws://127.0.0.1:9222" # WebSocket 目标
 
 
 
 
11
 
12
  @app.api_route("/{path:path}", methods=["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS", "HEAD"])
13
  async def proxy(request: Request, path: str):
14
-
15
  url = f"{TARGET_BASE}/{path}"
16
  headers = dict(request.headers)
17
- host = headers["host"]
18
- # 强制 Host 头为 127.0.0.1,避免 Chrome 拒绝
19
- headers["host"] = "127.0.0.1"
20
  body = await request.body()
21
  async with httpx.AsyncClient(follow_redirects=True) as client:
22
  resp = await client.request(
@@ -26,35 +28,44 @@ async def proxy(request: Request, path: str):
26
  content=body,
27
  params=request.query_params
28
  )
29
- headers = dict(resp.headers)
30
- headers["host"] = host
31
  return Response(
32
  content=resp.content,
33
  status_code=resp.status_code,
34
- headers=headers
35
  )
36
 
37
  @app.websocket("/{path:path}")
38
  async def websocket_proxy(websocket: WebSocket, path: str):
39
  await websocket.accept()
40
  target_url = f"{TARGET_WS_BASE}/{path}"
 
 
41
  try:
42
- async with websockets.connect(target_url, extra_headers={"Host": "127.0.0.1"}) as target_ws:
 
 
 
 
 
43
  async def client_to_server():
44
  while True:
45
- data = await websocket.receive_text()
46
  await target_ws.send(data)
47
 
48
  async def server_to_client():
49
  while True:
50
  data = await target_ws.recv()
51
- await websocket.send_text(data)
 
 
 
52
 
53
  await asyncio.gather(client_to_server(), server_to_client())
54
  except WebSocketDisconnect:
55
- pass
56
- except Exception:
 
57
  await websocket.close()
58
 
59
  if __name__ == "__main__":
60
- uvicorn.run("fun:app", host="0.0.0.0", port=8000)
 
1
+ from fastapi import FastAPI, Request, Response, WebSocket, WebSocketDisconnect
2
  import httpx
3
  import uvicorn
4
  import asyncio
5
  import websockets
6
+ import logging
7
 
8
  app = FastAPI()
9
 
10
+ TARGET_BASE = "http://127.0.0.1:9222" # Chrome DevTools HTTP 地址
11
+ TARGET_WS_BASE = "ws://127.0.0.1:9222" # Chrome DevTools WebSocket 地址
12
+
13
+ # 配置日志
14
+ logging.basicConfig(level=logging.INFO)
15
+ logger = logging.getLogger(__name__)
16
 
17
  @app.api_route("/{path:path}", methods=["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS", "HEAD"])
18
  async def proxy(request: Request, path: str):
 
19
  url = f"{TARGET_BASE}/{path}"
20
  headers = dict(request.headers)
21
+ headers["host"] = "127.0.0.1" # 强制修改 Host 头
 
 
22
  body = await request.body()
23
  async with httpx.AsyncClient(follow_redirects=True) as client:
24
  resp = await client.request(
 
28
  content=body,
29
  params=request.query_params
30
  )
 
 
31
  return Response(
32
  content=resp.content,
33
  status_code=resp.status_code,
34
+ headers=dict(resp.headers)
35
  )
36
 
37
  @app.websocket("/{path:path}")
38
  async def websocket_proxy(websocket: WebSocket, path: str):
39
  await websocket.accept()
40
  target_url = f"{TARGET_WS_BASE}/{path}"
41
+ logger.info(f"Forwarding WebSocket to: {target_url}")
42
+
43
  try:
44
+ async with websockets.connect(
45
+ target_url,
46
+ extra_headers={"Host": "127.0.0.1"},
47
+ ping_timeout=30,
48
+ close_timeout=10
49
+ ) as target_ws:
50
  async def client_to_server():
51
  while True:
52
+ data = await websocket.receive_bytes() # 支持二进制
53
  await target_ws.send(data)
54
 
55
  async def server_to_client():
56
  while True:
57
  data = await target_ws.recv()
58
+ if isinstance(data, bytes):
59
+ await websocket.send_bytes(data)
60
+ else:
61
+ await websocket.send_text(data)
62
 
63
  await asyncio.gather(client_to_server(), server_to_client())
64
  except WebSocketDisconnect:
65
+ logger.info("Client disconnected")
66
+ except Exception as e:
67
+ logger.error(f"WebSocket error: {e}")
68
  await websocket.close()
69
 
70
  if __name__ == "__main__":
71
+ uvicorn.run("hg:app", host="0.0.0.0", port=8000, reload=True)