-
Notifications
You must be signed in to change notification settings - Fork 0
/
reverse_proxy.py
51 lines (38 loc) · 1.56 KB
/
reverse_proxy.py
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
import json
import httpx
from fastapi import FastAPI, Request
from starlette.responses import Response
app = FastAPI()
TARGET_URL = "http://openrouter.ai/api/v1" # Target URL to forward the requests to
@app.api_route("/{path:path}", methods=["GET", "POST", "PUT", "DELETE"])
async def forward(request: Request, path: str):
body = await request.body()
# Log the request body, consider logging more information as needed
body_str = body.decode("utf-8")
body_str = json.loads(body_str) if body_str else {}
print("Request Body String:", json.dumps(body_str, indent=4))
# Prepare the request to forward
method = request.method
headers = dict(request.headers)
auth_header = request.headers.get("Authorization")
if auth_header:
headers["Authorization"] = auth_header
# Remove the host header since it will be replaced with the target URL's host
headers.pop("host", None)
headers["host"] = "openrouter.ai"
async with httpx.AsyncClient() as client:
# Forward the request to the target URL
target_url = f"{TARGET_URL}/{path}"
print(f"Forwarding {method} request to {target_url}")
response = await client.request(
method, target_url, content=body, headers=headers
)
# Return the response received from the target URL
return Response(
content=response.content,
status_code=response.status_code,
headers=dict(response.headers),
)
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)