Created
October 22, 2025 17:22
-
-
Save AldeRoberge/a636bc8c376554ec0595162e139dd3de to your computer and use it in GitHub Desktop.
A local server with configurable port and folder to quickly get your WebGL build running on localhost.
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 sys | |
| from http.server import SimpleHTTPRequestHandler, HTTPServer | |
| import os | |
| class CompressedRequestHandler(SimpleHTTPRequestHandler): | |
| """HTTP handler that supports gzip (.gz) and Brotli (.br) files.""" | |
| def end_headers(self): | |
| """Set Content-Encoding header for compressed files.""" | |
| if self.path.endswith('.gz'): | |
| self.send_header('Content-Encoding', 'gzip') | |
| elif self.path.endswith('.br'): | |
| self.send_header('Content-Encoding', 'br') | |
| super().end_headers() | |
| def do_GET(self): | |
| """Serve compressed files with correct Content-Type.""" | |
| path = self.translate_path(self.path) | |
| if os.path.isfile(path): | |
| # Serve .js.gz | |
| if path.endswith('.js.gz'): | |
| self.send_response(200) | |
| self.send_header('Content-Type', 'application/javascript') | |
| self.end_headers() | |
| with open(path, 'rb') as f: | |
| self.wfile.write(f.read()) | |
| return | |
| # Serve .wasm.gz | |
| elif path.endswith('.wasm.gz'): | |
| self.send_response(200) | |
| self.send_header('Content-Type', 'application/wasm') | |
| self.end_headers() | |
| with open(path, 'rb') as f: | |
| self.wfile.write(f.read()) | |
| return | |
| # Serve other .gz files | |
| elif path.endswith('.gz'): | |
| self.send_response(200) | |
| self.send_header('Content-Type', self.guess_type(path)) | |
| self.end_headers() | |
| with open(path, 'rb') as f: | |
| self.wfile.write(f.read()) | |
| return | |
| # Serve .br files | |
| elif path.endswith('.br'): | |
| original_path = path[:-3] # remove .br | |
| self.send_response(200) | |
| self.send_header('Content-Type', self.guess_type(original_path)) | |
| self.end_headers() | |
| with open(path, 'rb') as f: | |
| self.wfile.write(f.read()) | |
| return | |
| # fallback to default handler | |
| super().do_GET() | |
| def serve(port: int): | |
| """Run local HTTP server.""" | |
| httpd = HTTPServer(('localhost', port), CompressedRequestHandler) | |
| print(f"Serving at http://localhost:{port}") | |
| httpd.serve_forever() | |
| if __name__ == "__main__": | |
| try: | |
| if len(sys.argv) != 2: | |
| print(f'Usage: {sys.argv[0]} [PORT]') | |
| sys.exit(1) | |
| port = int(sys.argv[1]) | |
| serve(port) | |
| except Exception as e: | |
| print('Error:', e) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment