Last active
February 8, 2025 18:19
-
-
Save sinedsem/4c9727097f76648b697aaa7b1a289054 to your computer and use it in GitHub Desktop.
Python web server for Unity WebGL
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import http.server | |
| import socketserver | |
| import mimetypes | |
| import ssl | |
| import argparse | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("-p", "--port", type=int, default=8080, help="Port (default: 8080)") | |
| parser.add_argument("-d", "--dir", type=str, default="./Build", help="Folder (default: ./Build)") | |
| args = parser.parse_args() | |
| PORT = args.port | |
| DIRECTORY = args.dir | |
| class CustomRequestHandler(http.server.SimpleHTTPRequestHandler): | |
| def __init__(self, *args, **kwargs): | |
| super().__init__(*args, directory=DIRECTORY, **kwargs) | |
| def guess_type(self, path): | |
| base, ext = mimetypes.guess_type(path) | |
| if ".wasm." in path or path.endswith(".wasm"): | |
| return "application/wasm" | |
| if ".data." in path or path.endswith(".data"): | |
| return "application/octet-stream" | |
| if ".js." in path or path.endswith(".js"): | |
| return "application/javascript" | |
| return base | |
| def end_headers(self): | |
| self.send_header('Access-Control-Allow-Origin', '*') | |
| if self.path.endswith(".br"): | |
| self.send_header("Content-Encoding", "br") | |
| super().end_headers() | |
| with http.server.ThreadingHTTPServer(("", PORT), CustomRequestHandler) as httpd: | |
| # old https | |
| # httpd.socket = ssl.wrap_socket(httpd.socket, certfile="server.pem", server_side=True) | |
| # new https: | |
| # context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) | |
| # context.load_cert_chain(certfile="server.pem") | |
| # httpd.socket = context.wrap_socket(httpd.socket, server_side=True) | |
| print(f"Serving at localhost:{PORT} from directory {DIRECTORY}") | |
| try: | |
| httpd.serve_forever() | |
| except KeyboardInterrupt: | |
| print("Shutting down the server...") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment