from fastapi import FastAPI, Request, Response, status import httpx import uvicorn import time app = FastAPI() time.sleep(10) TARGET_BASE = "http://127.0.0.1:9222" # 替换为你的目标服务器 resp = httpx.get(TARGET_BASE) print(f'RESP:{resp.text}') @app.api_route("/{path:path}", methods=["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS", "HEAD"]) async def proxy(request: Request, path: str): resp = httpx.get(TARGET_BASE) # 强制Host头为127.0.0.1 print(f'RESP:{resp.text}') # if path == "": # # 拒绝根目录 # return Response(content="Not Found", status_code=status.HTTP_404_NOT_FOUND) url = f"{TARGET_BASE}/{path}" headers = dict(request.headers) host = headers["host"] headers["host"] = "127.0.0.1" body = await request.body() async with httpx.AsyncClient(follow_redirects=True) as client: resp = await client.request( request.method, url, headers=headers, content=body, params=request.query_params ) headers = dict(resp.headers) headers["host"] = host return Response( content=resp.content, status_code=resp.status_code, headers=headers ) if __name__ == "__main__": # 运行FastAPI应用 uvicorn.run("fun:app", host="0.0.0.0", port=8000)