File size: 2,011 Bytes
b451c6e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#!/usr/bin/env python3
"""
Local development server for cloze-reader
Serves static files with CORS enabled for local testing
"""

import http.server
import socketserver
import os
from urllib.parse import urlparse
import json

class LocalHandler(http.server.SimpleHTTPRequestHandler):
    def end_headers(self):
        # Enable CORS for local development
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'Content-Type')
        super().end_headers()
    
    def do_GET(self):
        # Handle root path
        if self.path == '/':
            self.path = '/index.html'
        
        # Handle icon.png (serve local file if exists, otherwise redirect)
        if self.path == '/icon.png':
            if os.path.exists('icon.png'):
                return super().do_GET()
            else:
                self.send_response(302)
                self.send_header('Location', 'https://raw.githubusercontent.com/zmuhls/cloze-reader/main/icon.png')
                self.end_headers()
                return
        
        # Serve static files
        return super().do_GET()
    
    def do_OPTIONS(self):
        self.send_response(200)
        self.end_headers()

def run_server(port=8000):
    handler = LocalHandler
    
    try:
        with socketserver.TCPServer(("", port), handler) as httpd:
            print(f"Local development server running at http://localhost:{port}/")
            print("Press Ctrl+C to stop")
            httpd.serve_forever()
    except KeyboardInterrupt:
        print("\nServer stopped")
    except OSError as e:
        if e.errno == 48:  # Address already in use
            print(f"Port {port} is already in use. Try a different port.")
        else:
            print(f"Error starting server: {e}")

if __name__ == "__main__":
    import sys
    port = int(sys.argv[1]) if len(sys.argv) > 1 else 8000
    run_server(port)