navigation: move extract_port here

This commit is contained in:
dece 2021-06-05 01:27:12 +02:00
parent f157993946
commit 68bc524117
2 changed files with 21 additions and 10 deletions

View file

@ -176,3 +176,16 @@ def get_root_url(url: str) -> str:
parts["path"] = "/" parts["path"] = "/"
clear_post_path(parts) clear_post_path(parts)
return unparse_url(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

View file

@ -9,6 +9,7 @@ from enum import IntEnum
from typing import Optional from typing import Optional
from bebop.mime import DEFAULT_MIME_TYPE, MimeType from bebop.mime import DEFAULT_MIME_TYPE, MimeType
from bebop.navigation import parse_host_and_port
from bebop.tofu import CertStatus, validate_cert from bebop.tofu import CertStatus, validate_cert
@ -127,16 +128,13 @@ class Request:
if not url_parts: if not url_parts:
self.state = Request.STATE_INVALID_URL self.state = Request.STATE_INVALID_URL
return False return False
hostname = url_parts.groupdict()["host"]
if ":" in hostname: host = url_parts.groupdict()["host"]
hostname, port = hostname.split(":", maxsplit=1) host_and_port = parse_host_and_port(host, 1965)
try: if host_and_port is None:
port = int(port)
except ValueError:
self.state = Request.STATE_INVALID_URL self.state = Request.STATE_INVALID_URL
return False return False
else: hostname, port = host_and_port
port = 1965
self.hostname = hostname self.hostname = hostname
# Prepare the Gemini request. # Prepare the Gemini request.