Skip to content

Commit c49df2b

Browse files
committed
scripts/serve: Optionally serve over https.
Allows local testing on mobile devices with Bluetooth, USB, and camera suppport.
1 parent 38a7123 commit c49df2b

1 file changed

Lines changed: 16 additions & 6 deletions

File tree

scripts/serve.py

Lines changed: 16 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,11 @@
66

77
import http.server
88
import pathlib
9-
import socketserver
9+
import ssl
1010

1111
BUILD_DIR = (pathlib.Path(__file__).parent.parent / "build").resolve()
12+
CERT_FILE = BUILD_DIR / "cert.pem"
13+
KEY_FILE = BUILD_DIR / "key.pem"
1214
PORT = 8000
1315

1416

@@ -17,10 +19,10 @@ def __init__(
1719
self,
1820
request: bytes,
1921
client_address: tuple[str, int],
20-
server: socketserver.BaseServer,
22+
server: http.server.HTTPServer,
2123
directory: str | None = ...
2224
) -> None:
23-
super().__init__(request, client_address, server, directory=BUILD_DIR)
25+
super().__init__(request, client_address, server, directory=str(BUILD_DIR))
2426

2527
def end_headers(self) -> None:
2628
# custom headers needed for some web API features
@@ -29,6 +31,14 @@ def end_headers(self) -> None:
2931
return super().end_headers()
3032

3133

32-
with socketserver.TCPServer(("", PORT), Handler) as httpd:
33-
print(f"serving at http://0.0.0.0:{PORT}")
34-
httpd.serve_forever()
34+
httpd = http.server.HTTPServer(("", PORT), Handler)
35+
36+
if CERT_FILE.exists() and KEY_FILE.exists():
37+
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
38+
ctx.load_cert_chain(certfile=CERT_FILE, keyfile=KEY_FILE)
39+
httpd.socket = ctx.wrap_socket(httpd.socket, server_side=True)
40+
print(f"serving at https://0.0.0.0:{PORT}")
41+
else:
42+
print(f"cert/key not found, serving without TLS at http://0.0.0.0:{PORT}")
43+
44+
httpd.serve_forever()

0 commit comments

Comments
 (0)