diff --git a/server.py b/server.py index 96c4407..18544c3 100644 --- a/server.py +++ b/server.py @@ -91,23 +91,27 @@ async def register_service(name: str, ip: str): async def read_service(name: str): """Reads the hosts file, produces a service catalog entry.""" catalog = {} - - with open(HOSTS_FILE, "r") as fd: - hosts_file = fd.read().split("\n") - entries = [ - entry for entry in hosts_file if not entry.startswith("#") and entry != "\n" - ] - for entry in entries: - match = re.match(r"\s*(\d+\.\d+\.\d+\.\d+)\s+(.+)", entry) - if match: - ip_address = match.group(1) - hostnames = match.group(2).split() - for hostname in hostnames: - if hostname not in catalog: - catalog[hostname] = [ip_address] - else: - catalog[hostname].append(ip_address) - return catalog[name] + try: + with open(HOSTS_FILE, "r") as fd: + hosts_file = fd.read().split("\n") + entries = [ + entry + for entry in hosts_file + if not entry.startswith("#") and entry != "\n" + ] + for entry in entries: + match = re.match(r"\s*(\d+\.\d+\.\d+\.\d+)\s+(.+)", entry) + if match: + ip_address = match.group(1) + hostnames = match.group(2).split() + for hostname in hostnames: + if hostname not in catalog: + catalog[hostname] = [ip_address] + else: + catalog[hostname].append(ip_address) + return catalog[name] + except KeyError: + raise HTTPException(status_code=404, detail=f"Service not found: {name}") @app.get("/services")