Skip to content
Open
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 26 additions & 7 deletions scripts/server_with_rewrites.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,28 @@
from http.server import HTTPServer, SimpleHTTPRequestHandler
import argparse

class MyHTTPServer(HTTPServer):
def __init__(self, server_address, RequestHandlerClass,
base_path='',
bind_and_activate=True):
HTTPServer.__init__(self, server_address, RequestHandlerClass, bind_and_activate=bind_and_activate)
self.base_path = base_path
Comment thread
tilusnet marked this conversation as resolved.
Outdated

class RequestHandler(SimpleHTTPRequestHandler):

class RequestHandler(SimpleHTTPRequestHandler):
# mimic firebase hosting's rewrite rules
def translate_path(self, path):
if path.startswith('/simplified') or path.startswith('/traditional') or path.startswith('/cantonese') or path.startswith('/hsk'):
def translate_path(self, request_path):
base_path = self.server.base_path if isinstance(self.server, MyHTTPServer) else ''
slashed_path = request_path.removeprefix(base_path)
crit_blank = slashed_path in ('/', '')
crit_specials = any([slashed_path.startswith(f"{candidate}") for candidate in (
'/simplified', '/traditional', '/cantonese', '/hsk'
)])
if crit_blank or crit_specials:
return 'index.html'
# prepend . such that the frontend's use of /whatever results in ./whatever
# should maybe just strip the first character, tbh
return f".{path}"
# now turn the slashed path /foo/bar into ./foo/bar on disk
path = f".{slashed_path}"
Comment thread
tilusnet marked this conversation as resolved.
return path


if __name__ == '__main__':
Expand All @@ -20,9 +32,16 @@ def translate_path(self, path):
description='Enable URL rewrites without relying on firebase hosting. Intended to be run from the public/ directory.')
parser.add_argument(
'--port', help='your choice of port; default 8000', nargs='?', default=8000, type=int)
parser.add_argument(
'--base-path', help='custom base path, e.g. /app/hanzi; useful for reverse proxy', default='')
args = parser.parse_args()
port = int(args.port)
myServer = HTTPServer(('0.0.0.0', port), RequestHandler)
base_path = args.base_path
if base_path:
assert base_path[0] == '/', '--base-path must start with /'
if base_path[-1] == '/':
base_path = base_path[:-1]
myServer = MyHTTPServer(('0.0.0.0', port), RequestHandler, base_path=base_path)
print("HanziGraph started")
try:
myServer.serve_forever()
Expand Down