diff options
author | Rémi Verschelde <rverschelde@gmail.com> | 2022-10-05 08:36:19 +0200 |
---|---|---|
committer | Rémi Verschelde <rverschelde@gmail.com> | 2022-10-05 08:36:19 +0200 |
commit | 4bf31990007717fb9e2bffcc882d48274f23916c (patch) | |
tree | 75c8d8a4c217e346911dc04281650ce071f6ccc5 /platform/web/serve.py | |
parent | 3a2b0ab73d4cfbed769d46517f1f4832a975a979 (diff) | |
parent | 1be1b15a57eb74d3c8d56683e6a221fd4712915c (diff) |
Merge pull request #64886 from Calinou/web-editor-add-local-web-server-2
Replace local web server setup for web editor with a Python-based solution
Diffstat (limited to 'platform/web/serve.py')
-rwxr-xr-x | platform/web/serve.py | 52 |
1 files changed, 52 insertions, 0 deletions
diff --git a/platform/web/serve.py b/platform/web/serve.py new file mode 100755 index 0000000000..14e87e9ea1 --- /dev/null +++ b/platform/web/serve.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python3 + +from http.server import HTTPServer, SimpleHTTPRequestHandler, test # type: ignore +from pathlib import Path +import os +import sys +import argparse +import subprocess + + +class CORSRequestHandler(SimpleHTTPRequestHandler): + def end_headers(self): + self.send_header("Cross-Origin-Opener-Policy", "same-origin") + self.send_header("Cross-Origin-Embedder-Policy", "require-corp") + self.send_header("Access-Control-Allow-Origin", "*") + super().end_headers() + + +def shell_open(url): + if sys.platform == "win32": + os.startfile(url) + else: + opener = "open" if sys.platform == "darwin" else "xdg-open" + subprocess.call([opener, url]) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("-p", "--port", help="port to listen on", default=8060, type=int) + parser.add_argument( + "-r", "--root", help="path to serve as root (relative to `platform/web/`)", default="../../bin", type=Path + ) + browser_parser = parser.add_mutually_exclusive_group(required=False) + browser_parser.add_argument( + "-n", "--no-browser", help="don't open default web browser automatically", dest="browser", action="store_false" + ) + parser.set_defaults(browser=True) + args = parser.parse_args() + + # Change to the directory where the script is located, + # so that the script can be run from any location. + os.chdir(Path(__file__).resolve().parent) + + if args.root: + os.chdir(args.root) + + if args.browser: + # Open the served page in the user's default browser. + print("Opening the served URL in the default browser (use `--no-browser` or `-n` to disable this).") + shell_open(f"http://127.0.0.1:{args.port}") + + test(CORSRequestHandler, HTTPServer, port=args.port) |