serve.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  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. if __name__ == "__main__":
  21. parser = argparse.ArgumentParser()
  22. parser.add_argument("-p", "--port", help="port to listen on", default=8060, type=int)
  23. parser.add_argument(
  24. "-r", "--root", help="path to serve as root (relative to `platform/web/`)", default="../../bin", type=Path
  25. )
  26. browser_parser = parser.add_mutually_exclusive_group(required=False)
  27. browser_parser.add_argument(
  28. "-n", "--no-browser", help="don't open default web browser automatically", dest="browser", action="store_false"
  29. )
  30. parser.set_defaults(browser=True)
  31. args = parser.parse_args()
  32. # Change to the directory where the script is located,
  33. # so that the script can be run from any location.
  34. os.chdir(Path(__file__).resolve().parent)
  35. if args.root:
  36. os.chdir(args.root)
  37. if args.browser:
  38. # Open the served page in the user's default browser.
  39. print("Opening the served URL in the default browser (use `--no-browser` or `-n` to disable this).")
  40. shell_open(f"http://127.0.0.1:{args.port}")
  41. test(CORSRequestHandler, HTTPServer, port=args.port)