Repository navigation
Expand file tree
/
Copy pathserve.py
More file actions
53 lines (45 loc) · 2.11 KB
/
Copy pathserve.py
File metadata and controls
53 lines (45 loc) · 2.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#!/usr/bin/env python3
# SPDX-License-Identifier: AGPL-3.0-or-later
# Local preview server for TestnetHub. The deployed pages link to clean,
# extensionless URLs (/faucet), which Cloudflare Pages serves from faucet.html.
# Python's plain http.server does NOT do that mapping, so this tiny wrapper does:
# it serves /foo from foo.html and falls back to 404.html, matching production.
#
# python3 serve.py # then open http://localhost:8000
# python3 serve.py 8080 # custom port
#
# Run `python3 build.py` first (or after any edit) to regenerate the pages.
import os
import sys
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
ROOT = os.path.dirname(os.path.abspath(__file__))
class Handler(SimpleHTTPRequestHandler):
def __init__(self, *a, **k):
super().__init__(*a, directory=ROOT, **k)
def translate_path(self, path):
# Map a clean URL to its .html file when the extensionless path has no
# real file/dir of its own (mirrors Cloudflare Pages behaviour).
clean = path.split("?", 1)[0].split("#", 1)[0]
fs = super().translate_path(path)
if clean.endswith("/"):
return fs
if not os.path.exists(fs) and os.path.isfile(fs + ".html"):
return fs + ".html"
return fs
def send_error(self, code, message=None, explain=None):
# Serve the styled 404 page for missing routes, like production.
if code == 404:
page = os.path.join(ROOT, "404.html")
if os.path.isfile(page):
body = open(page, "rb").read()
self.send_response(404)
self.send_header("Content-Type", "text/html; charset=utf-8")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
return
super().send_error(code, message, explain)
if __name__ == "__main__":
port = int(sys.argv[1]) if len(sys.argv) > 1 else 8000
print(f"TestnetHub preview: http://localhost:{port} (Ctrl+C to stop)")
ThreadingHTTPServer(("127.0.0.1", port), Handler).serve_forever()