Back to home page

Project CMSSW displayed by LXR

 
 

    


File indexing completed on 2025-04-30 22:24:13

0001 import os
0002 from http.server import HTTPServer, SimpleHTTPRequestHandler
0003 import mimetypes
0004 import argparse
0005 import json
0006 
0007 class Serv(SimpleHTTPRequestHandler):
0008     def do_GET(self):
0009         # Default route to serve the index.html file
0010         if self.path == '/':
0011             self.path = '/index.html'
0012         elif self.path == '/list-json':
0013             self.send_response(200)
0014             self.send_header('Content-type', 'application/json')
0015             self.end_headers()
0016             json_files = sorted([f for f in os.listdir('.') if f.endswith('.json')])
0017             self.wfile.write(json.dumps(json_files).encode())
0018             return
0019 
0020         # Serve the requested file (JSON or other static files)
0021         file_path = self.path[1:]  # Remove leading '/' to get the file path
0022 
0023         try:
0024             # Read the requested file
0025             with open(file_path, 'rb') as file:
0026                 file_to_open = file.read()
0027 
0028             # MIME type of the file
0029             mime_type, _ = mimetypes.guess_type(file_path)
0030 
0031             # Send the HTTP response
0032             self.send_response(200)
0033             if mime_type:
0034                 self.send_header("Content-type", mime_type)
0035             self.end_headers()
0036 
0037             # Write the file content to the response
0038             self.wfile.write(file_to_open)
0039 
0040         except FileNotFoundError:
0041             # Handle file not found error
0042             self.send_response(404)
0043             self.send_header("Content-type", "text/html")
0044             self.end_headers()
0045             self.wfile.write(bytes("File not found", 'utf-8'))
0046 
0047         except Exception as e:
0048             # Handle any other internal server errors
0049             self.send_response(500)
0050             self.send_header("Content-type", "text/html")
0051             self.end_headers()
0052             self.wfile.write(bytes(f"Internal server error: {str(e)}", 'utf-8'))
0053 
0054 def run(server_class=HTTPServer, handler_class=Serv, port=65432):
0055     # Configure and start the HTTP server
0056     server_address = ('localhost', port)
0057     httpd = server_class(server_address, handler_class)
0058     print(f"Server started at http://localhost:{port}")
0059     httpd.serve_forever()
0060 
0061 if __name__ == "__main__":
0062     # Parse command-line arguments to set the server port
0063     parser = argparse.ArgumentParser(description='Start a simple HTTP server.')
0064     parser.add_argument('--port', type=int, default=65432, help='Port to serve on (default: 65432)')
0065     args = parser.parse_args()
0066 
0067     # Start the server with the specified port
0068     run(port=args.port)
0069 
0070 
0071