from fastapi import FastAPI, HTTPException from fastapi.middleware.cors import CORSMiddleware import socket import asyncio app = FastAPI() # Configure CORS app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"], ) async def check_port(host: str, port: int, timeout: float = 2.0) -> bool: try: # Create async socket connection reader, writer = await asyncio.wait_for( asyncio.open_connection(host, port), timeout=timeout ) writer.close() await writer.wait_closed() return True except (socket.gaierror, ConnectionRefusedError, asyncio.TimeoutError): return False except Exception: return False @app.get("/check-port") async def port_check(host: str, port: int): is_alive = await check_port(host, port) return {"status": "online" if is_alive else "offline"} @app.get("/health") async def health_check(): return {"status": "ok"}