diff --git a/bebop/navigation.py b/bebop/navigation.py index dcaa8c3..d4de50c 100644 --- a/bebop/navigation.py +++ b/bebop/navigation.py @@ -176,3 +176,16 @@ def get_root_url(url: str) -> str: parts["path"] = "/" clear_post_path(parts) return unparse_url(parts) + + +def parse_host_and_port(host: str, default_port: int): + """Return the host and port from a "host:port" string.""" + if ":" in host: + host, port = host.split(":", maxsplit=1) + try: + port = int(port) + except ValueError: + return None + else: + port = default_port + return host, port diff --git a/bebop/protocol.py b/bebop/protocol.py index 20c14d3..42f860a 100644 --- a/bebop/protocol.py +++ b/bebop/protocol.py @@ -9,6 +9,7 @@ from enum import IntEnum from typing import Optional from bebop.mime import DEFAULT_MIME_TYPE, MimeType +from bebop.navigation import parse_host_and_port from bebop.tofu import CertStatus, validate_cert @@ -127,16 +128,13 @@ class Request: if not url_parts: self.state = Request.STATE_INVALID_URL return False - hostname = url_parts.groupdict()["host"] - if ":" in hostname: - hostname, port = hostname.split(":", maxsplit=1) - try: - port = int(port) - except ValueError: - self.state = Request.STATE_INVALID_URL - return False - else: - port = 1965 + + host = url_parts.groupdict()["host"] + host_and_port = parse_host_and_port(host, 1965) + if host_and_port is None: + self.state = Request.STATE_INVALID_URL + return False + hostname, port = host_and_port self.hostname = hostname # Prepare the Gemini request.