From 0b883d30e420723be2aa8f296b71f27830ebcc8a Mon Sep 17 00:00:00 2001 From: ache Date: Sat, 22 Apr 2023 01:30:35 +0200 Subject: Update 404 stategy --- pyhttpd.py | 52 +++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 51 insertions(+), 1 deletion(-) diff --git a/pyhttpd.py b/pyhttpd.py index 2ca1eda..bd546a7 100644 --- a/pyhttpd.py +++ b/pyhttpd.py @@ -2,7 +2,9 @@ """Use this instead of `python3 -m http.server` when you need CORS""" from http.server import HTTPServer, SimpleHTTPRequestHandler +from pathlib import Path +serverHost = ('localhost', 8080) class CORSRequestHandler(SimpleHTTPRequestHandler): def end_headers(self): @@ -11,6 +13,54 @@ class CORSRequestHandler(SimpleHTTPRequestHandler): 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) + + +httpd = HTTPServer(serverHost, CORSRequestHandler) + +# Print the server's host and port +print(f"Listening on {serverHost[0]} port {serverHost[1]}") + -httpd = HTTPServer(('localhost', 8080), CORSRequestHandler) httpd.serve_forever() -- cgit v1.2.3