A fast, keyboard-driven TUI API client & webhook inspector. No cloud, no Electron, 100% local-first.
feat(backend): implement local webhook listener and async HTTP client
4yk59c59b584c7b2
diff --git a/network.py b/network.pynew file mode 100644index 0000000..ecb8b68--- /dev/null+++ b/network.py@@ -0,0 +1,59 @@+import time+import json+import httpx++class NetworkEngine:+ def __init__(self, timeout: float = 15.0):+ self.timeout = timeout++ async def execute_request(self, method: str, url: str, headers: dict = None, body: str = None):+ start_time = time.perf_counter()+ headers = dict(headers) if headers else {}++ if not any(k.lower() == "user-agent" for k in headers):+ headers["User-Agent"] = "Ghostman/0.1.0"++ if body and not any(k.lower() == "content-type" for k in headers):+ try:+ json.loads(body)+ headers["Content-Type"] = "application/json"+ except Exception:+ pass++ try:+ async with httpx.AsyncClient(verify=False, timeout=self.timeout, follow_redirects=True) as client:+ res = await client.request(+ method=method.upper(),+ url=url,+ headers=headers,+ content=body.encode("utf-8") if body else None+ )+ elapsed_ms = (time.perf_counter() - start_time) * 1000++ raw_text = res.text+ try:+ formatted_body = json.dumps(res.json(), indent=2, ensure_ascii=False)+ is_json = True+ except Exception:+ formatted_body = raw_text+ is_json = False++ return {+ "success": True,+ "status_code": res.status_code,+ "reason": res.reason_phrase,+ "elapsed_ms": round(elapsed_ms, 2),+ "headers": dict(res.headers),+ "body": formatted_body,+ "is_json": is_json,+ "size_bytes": len(res.content)+ }+ except Exception as e:+ elapsed_ms = (time.perf_counter() - start_time) * 1000+ return {+ "success": False,+ "error": str(e),+ "elapsed_ms": round(elapsed_ms, 2),+ "status_code": 0,+ "body": f"Request Failed: {e}"+ }diff --git a/webhook_server.py b/webhook_server.pynew file mode 100644index 0000000..480ec75--- /dev/null+++ b/webhook_server.py@@ -0,0 +1,96 @@+import asyncio+import json+from datetime import datetime+from typing import Callable, Optional++class WebhookServer:+ def __init__(self, host: str = "127.0.0.1", port: int = 9090, on_hook_received: Optional[Callable] = None):+ self.host = host+ self.port = port+ self.on_hook_received = on_hook_received+ self.server: Optional[asyncio.AbstractServer] = None+ self.is_running = False+ self.captured_hooks = []++ async def start(self):+ if self.is_running:+ return+ self.server = await asyncio.start_server(self._handle_client, self.host, self.port)+ self.is_running = True++ async def stop(self):+ if self.server:+ self.server.close()+ await self.server.wait_closed()+ self.server = None+ self.is_running = False++ async def _handle_client(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter):+ try:+ line = await reader.readline()+ if not line:+ writer.close()+ await writer.wait_closed()+ return++ req_line = line.decode("utf-8", errors="ignore").strip()+ parts = req_line.split(" ")+ method = parts[0] if parts else "GET"+ path = parts[1] if len(parts) > 1 else "/"++ headers = {}+ content_length = 0+ while True:+ header_line = await reader.readline()+ if not header_line or header_line in (b"\r\n", b"\n"):+ break+ decoded_header = header_line.decode("utf-8", errors="ignore").strip()+ if ":" in decoded_header:+ k, v = decoded_header.split(":", 1)+ k_clean = k.strip().title()+ v_clean = v.strip()+ headers[k_clean] = v_clean+ if k_clean.lower() == "content-length":+ try:+ content_length = int(v_clean)+ except ValueError:+ content_length = 0++ body_bytes = b""+ if content_length > 0:+ body_bytes = await reader.readexactly(content_length)++ body_str = body_bytes.decode("utf-8", errors="ignore")+ try:+ formatted_body = json.dumps(json.loads(body_str), indent=2, ensure_ascii=False)+ except Exception:+ formatted_body = body_str++ hook_entry = {+ "id": len(self.captured_hooks) + 1,+ "timestamp": datetime.now().strftime("%H:%M:%S"),+ "method": method,+ "path": path,+ "headers": headers,+ "body": formatted_body,+ "raw_body": body_str+ }+ self.captured_hooks.append(hook_entry)++ response = b"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nConnection: close\r\n\r\n{\"status\":\"ok\",\"source\":\"ghostman\"}"+ writer.write(response)+ await writer.drain()++ if self.on_hook_received:+ if asyncio.iscoroutinefunction(self.on_hook_received):+ await self.on_hook_received(hook_entry)+ else:+ self.on_hook_received(hook_entry)+ except Exception:+ pass+ finally:+ try:+ writer.close()+ await writer.wait_closed()+ except Exception:+ pass