|
1 | | -from http.server import HTTPServer, BaseHTTPRequestHandler |
2 | 1 | import os |
| 2 | +from http.server import HTTPServer, BaseHTTPRequestHandler |
3 | 3 | import mimetypes |
| 4 | +import argparse |
4 | 5 |
|
5 | 6 | class Serv(BaseHTTPRequestHandler): |
6 | 7 | def do_GET(self): |
| 8 | + # Default route to serve the index.html file |
7 | 9 | if self.path == '/': |
8 | 10 | self.path = '/index.html' |
9 | | - |
| 11 | + # Serve the uploaded JavaScript file if requested |
| 12 | + if self.path == '/modules_data.json': |
| 13 | + self.path = '/modules_data.json' |
| 14 | + |
10 | 15 | try: |
11 | | - file_path = self.path[1:] |
| 16 | + file_path = self.path[1:] # Remove leading '/' to get the file path |
12 | 17 |
|
| 18 | + # Read the requested file |
13 | 19 | with open(file_path, 'rb') as file: |
14 | 20 | file_to_open = file.read() |
15 | 21 |
|
| 22 | + # MIME type of the file |
16 | 23 | mime_type, _ = mimetypes.guess_type(file_path) |
17 | 24 |
|
| 25 | + # Send the HTTP response |
18 | 26 | self.send_response(200) |
19 | 27 | if mime_type: |
20 | 28 | self.send_header("Content-type", mime_type) |
21 | 29 | self.end_headers() |
22 | 30 |
|
| 31 | + # Write the file content to the response |
23 | 32 | self.wfile.write(file_to_open) |
24 | | - |
| 33 | + |
25 | 34 | except FileNotFoundError: |
| 35 | + # Handle file not found error |
26 | 36 | self.send_response(404) |
27 | 37 | self.send_header("Content-type", "text/html") |
28 | 38 | self.end_headers() |
29 | 39 | self.wfile.write(bytes("File not found", 'utf-8')) |
30 | | - |
| 40 | + |
31 | 41 | except Exception as e: |
| 42 | + # Handle any other internal server errors |
32 | 43 | self.send_response(500) |
33 | 44 | self.send_header("Content-type", "text/html") |
34 | 45 | self.end_headers() |
35 | 46 | self.wfile.write(bytes(f"Internal server error: {str(e)}", 'utf-8')) |
36 | 47 |
|
37 | | -httpd = HTTPServer(('localhost', 65432), Serv) |
38 | | -print("Server started at http://localhost:65432") |
39 | | -httpd.serve_forever() |
| 48 | +def run(server_class=HTTPServer, handler_class=Serv, port=65432): |
| 49 | + # Configure and start the HTTP server |
| 50 | + server_address = ('localhost', port) |
| 51 | + httpd = server_class(server_address, handler_class) |
| 52 | + print(f"Server started at http://localhost:{port}") |
| 53 | + httpd.serve_forever() |
| 54 | + |
| 55 | +if __name__ == "__main__": |
| 56 | + # Parse command-line arguments to set the server port |
| 57 | + parser = argparse.ArgumentParser(description='Start a simple HTTP server.') |
| 58 | + parser.add_argument('--port', type=int, default=65432, help='Port to serve on (default: 65432)') |
| 59 | + args = parser.parse_args() |
| 60 | + |
| 61 | + # Start the server with the specified port |
| 62 | + run(port=args.port) |
| 63 | + |
0 commit comments