aboutsummaryrefslogtreecommitdiff
path: root/pyhttpd.py
diff options
context:
space:
mode:
Diffstat (limited to 'pyhttpd.py')
-rw-r--r--pyhttpd.py74
1 files changed, 74 insertions, 0 deletions
diff --git a/pyhttpd.py b/pyhttpd.py
new file mode 100644
index 0000000..78bd156
--- /dev/null
+++ b/pyhttpd.py
@@ -0,0 +1,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()