serve.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #!/usr/bin/env python3
  2. from http.server import HTTPServer, SimpleHTTPRequestHandler, test # type: ignore
  3. from pathlib import Path
  4. import os
  5. import sys
  6. import argparse
  7. import subprocess
  8. class CORSRequestHandler(SimpleHTTPRequestHandler):
  9. def end_headers(self):
  10. self.send_header("Cross-Origin-Opener-Policy", "same-origin")
  11. self.send_header("Cross-Origin-Embedder-Policy", "require-corp")
  12. self.send_header("Access-Control-Allow-Origin", "*")
  13. super().end_headers()
  14. def shell_open(url):
  15. if sys.platform == "win32":
  16. os.startfile(url)
  17. else:
  18. opener = "open" if sys.platform == "darwin" else "xdg-open"
  19. subprocess.call([opener, url])
  20. def serve(root, port, run_browser):
  21. os.chdir(root)
  22. if run_browser:
  23. # Open the served page in the user's default browser.
  24. print("Opening the served URL in the default browser (use `--no-browser` or `-n` to disable this).")
  25. shell_open(f"http://127.0.0.1:{port}")
  26. test(CORSRequestHandler, HTTPServer, port=port)
  27. if __name__ == "__main__":
  28. parser = argparse.ArgumentParser()
  29. parser.add_argument("-p", "--port", help="port to listen on", default=8060, type=int)
  30. parser.add_argument(
  31. "-r", "--root", help="path to serve as root (relative to `platform/web/`)", default="../../bin", type=Path
  32. )
  33. browser_parser = parser.add_mutually_exclusive_group(required=False)
  34. browser_parser.add_argument(
  35. "-n", "--no-browser", help="don't open default web browser automatically", dest="browser", action="store_false"
  36. )
  37. parser.set_defaults(browser=True)
  38. args = parser.parse_args()
  39. # Change to the directory where the script is located,
  40. # so that the script can be run from any location.
  41. os.chdir(Path(__file__).resolve().parent)
  42. serve(args.root, args.port, args.browser)