from fastapi import FastAPI, HTTPException from fastapi.middleware.cors import CORSMiddleware from pydantic import BaseModel import httpx import asyncio app = FastAPI() # Enable CORS app.add_middleware( CORSMiddleware, allow_origins=["*"], # Allows all origins allow_credentials=True, allow_methods=["*"], # Allows all methods allow_headers=["*"], # Allows all headers ) class ProxyTest(BaseModel): proxy: str @app.post("/test-proxy") async def test_proxy(proxy_test: ProxyTest): proxy = proxy_test.proxy test_url = "http://httpbin.org/ip" timeout = 10 try: async with httpx.AsyncClient(proxies={"http://": f"http://{proxy}", "https://": f"http://{proxy}"}) as client: start_time = asyncio.get_event_loop().time() response = await client.get(test_url, timeout=timeout) end_time = asyncio.get_event_loop().time() if response.status_code == 200: response_time = round((end_time - start_time) * 1000, 2) # Convert to milliseconds return { "status": "success", "message": f"Proxy {proxy} is working", "response_time": f"{response_time} ms" } else: raise HTTPException(status_code=400, detail=f"Proxy test failed with status code: {response.status_code}") except httpx.TimeoutException: raise HTTPException(status_code=408, detail=f"Proxy {proxy} timed out after {timeout} seconds") except Exception as e: raise HTTPException(status_code=400, detail=f"Proxy test failed: {str(e)}") if __name__ == "__main__": import uvicorn uvicorn.run(app, host="0.0.0.0", port=7860)