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
63
64
65
66
67
68
69
70
71
72
73
74
|
#!/usr/bin/env python3
"""Use this instead of `python3 -m http.server` when you need CORS"""
import argparse
from http.server import HTTPServer, SimpleHTTPRequestHandler
from pathlib import Path
class CORSRequestHandler(SimpleHTTPRequestHandler):
def end_headers(self):
self.send_header('Access-Control-Allow-Origin', '*')
self.send_header('Access-Control-Allow-Methods', '*')
self.send_header('Cache-Control', 'no-store, no-cache, must-revalidate')
return super(CORSRequestHandler, self).end_headers()
def do_POST(self):
# Redirect POST to the correct endpoint
if self.path.startswith('/like'):
self.send_response(307)
self.send_header('Location', f'http://localhost:3000{self.path}')
self.end_headers()
def do_GET(self):
# Redirect likes to the correct endpoint
if self.path.startswith('/like'):
self.send_response(302)
self.send_header('Location', f'http://localhost:3000{self.path}')
self.end_headers()
elif self.path == '/':
self.path = '/fr/index.html'
else:
path = Path('./' + self.path)
# Redirect to index
print(self.path)
print(path)
if path.is_dir():
self.path += '/index.html'
else:
# If it has not an extension add .html
if not path.suffix:
self.path += '.html'
print(self.path)
return super(CORSRequestHandler, self).do_GET()
def send_error(self, code, message=None):
if code == 404:
if self.path.endswith('/'):
pass
elif not self.path.endswith('.html'):
self.code = 304
self.redirect_to = self.path + '.html'
self.path += '.html'
self.end_headers()
SimpleHTTPRequestHandler.send_error(self, code, message)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Automaticaly set up a HTTP server')
parser.add_argument('-H', '--host', type=str, default='0.0.0.0', help='Host to serve on')
parser.add_argument('-p', '--port', type=int, default=8080, help='Port to serve on')
args = parser.parse_args()
host, port = args.host, args.port
# Print the server's host and port
print(f"Opening http://{host}:{port}", end='')
httpd = HTTPServer((host, port), CORSRequestHandler)
print(f"\rServed on http://{host}:{port}")
httpd.serve_forever()
|