| | |
| |
|
| | from fastapi import FastAPI, Request, HTTPException |
| | import re |
| | import httpx |
| |
|
| | app = FastAPI() |
| |
|
| | @app.get("/") |
| | def greet_json(): |
| | return {"Hello": "World!"} |
| |
|
| | @app.get("/v1/{dest_url:path}") |
| | async def gre_dest_url(dest_url: str): |
| | return dest_url |
| |
|
| | @app.post("/v1/{dest_url:path}") |
| | async def proxy_url(dest_url: str, request: Request): |
| | body = await request.body() |
| | headers = dict(request.headers) |
| | |
| | |
| | if 'content-length' in headers: |
| | del headers['content-length'] |
| | if 'host' in headers: |
| | del headers['host'] |
| | |
| | headers['User-Agent']='PostmanRuntime/7.43.0' |
| |
|
| | dest_url = re.sub('/', '://', dest_url, count=1) |
| |
|
| | async with httpx.AsyncClient() as client: |
| | try: |
| | |
| | response = await client.post(dest_url, content=body, headers=headers) |
| | |
| | |
| | if response.status_code == 200: |
| | |
| | if 'application/json' in response.headers.get('content-type', ''): |
| | return response.json() |
| | else: |
| | return {"error": "Response is not in JSON format"} |
| | else: |
| | |
| | try: |
| | error_data = response.json() |
| | except ValueError: |
| | error_data = {"status_code": response.status_code, "detail": response.text} |
| | return error_data |
| | |
| | except httpx.RequestError as e: |
| | |
| | raise HTTPException(status_code=500, detail=str(e)) |