diff options
author | ache <ache@ache.one> | 2023-04-22 01:30:35 +0200 |
---|---|---|
committer | ache <ache@ache.one> | 2023-04-22 01:32:57 +0200 |
commit | 0b883d30e420723be2aa8f296b71f27830ebcc8a (patch) | |
tree | da5dfd0dcd83bd235b08bbd083f461845b7f794b /pyhttpd.py | |
parent | Add pyhttpd (diff) |
Update 404 stategy
Diffstat (limited to 'pyhttpd.py')
-rw-r--r-- | pyhttpd.py | 52 |
1 files changed, 51 insertions, 1 deletions
@@ -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() |