opencode commited on
Commit
ae3fbab
·
1 Parent(s): 14eb040

feat: implement proxy server

Browse files
Files changed (2) hide show
  1. main.py +51 -0
  2. requirements.txt +3 -0
main.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, Request, Response, HTTPException
2
+ from fastapi.middleware.cors import CORSMiddleware
3
+ import httpx
4
+ import asyncio
5
+
6
+ app = FastAPI()
7
+
8
+ # The target Azure VM backend URL
9
+ TARGET_URL = "https://snap-providers-mercy-protocol.trycloudflare.com"
10
+
11
+ app.add_middleware(
12
+ CORSMiddleware,
13
+ allow_origins=["*"],
14
+ allow_methods=["*"],
15
+ allow_headers=["*"],
16
+ )
17
+
18
+ @app.api_route("/{path:path}", methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"])
19
+ async def proxy(request: Request, path: str):
20
+ \"\"\"Forwards all requests to the target backend.\"\"\"
21
+ url = f"{TARGET_URL}/{path}"
22
+
23
+ if request.method == "OPTIONS":
24
+ return Response(status_code=200)
25
+
26
+ async with httpx.AsyncClient() as client:
27
+ body = await request.body()
28
+ headers = dict(request.headers)
29
+ headers.pop("host", None)
30
+
31
+ try:
32
+ resp = await client.request(
33
+ method=request.method,
34
+ url=url,
35
+ headers=headers,
36
+ content=body,
37
+ timeout=60.0
38
+ )
39
+
40
+ # Return the original response from the backend
41
+ return Response(
42
+ content=resp.content,
43
+ status_code=resp.status_code,
44
+ headers=dict(resp.headers)
45
+ )
46
+ except httpx.RequestError as e:
47
+ raise HTTPException(status_code=502, detail=f"Proxy Error: {str(e)}")
48
+
49
+ if __name__ == "__main__":
50
+ import uvicorn
51
+ uvicorn.run(app, host="0.0.0.0", port=7860)
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ fastapi
2
+ uvicorn
3
+ httpx