From: Amin Bandali Date: Fri, 5 Nov 2021 05:14:44 +0000 (-0400) Subject: add custom python3 'serve' script based on http.server X-Git-Url: https://git.shemshak.org/gitweb.cgi/~bandali/bndl.org/commitdiff_plain/1742e66861e7a625034b4d2321604a8120a9f333?hp=f8427a27606990d96e95fe65007c4b2f79118a17 add custom python3 'serve' script based on http.server notably, has saner default mime type and encoding for txt files and files without extension. further, for a requested file X, if it does not exist, it will try X.html and X.txt as well (similar to nginx's try_files). --- diff --git a/serve b/serve new file mode 100755 index 0000000..1a9a21b --- /dev/null +++ b/serve @@ -0,0 +1,47 @@ +#!/usr/bin/env python3 + +# Copyright (c) 2021 bandali +# +# Copying and distribution of this file, with or without modification, +# are permitted in any medium without royalty provided the copyright +# notice and this notice are preserved. This file is offered as-is, +# without any warranty. + +import os +from http.server import SimpleHTTPRequestHandler +import socketserver + +try: + PORT = int(os.getenv('PORT', 8000)) +except ValueError: + print('PORT must be in integer') + exit(1) + +ADDR = os.getenv('ADDR', '127.0.0.1') + +class HttpRequestHandler(SimpleHTTPRequestHandler): + extensions_map = dict(SimpleHTTPRequestHandler.extensions_map) + extensions_map.update({'': 'text/plain;charset=UTF-8'}) + extensions_map.update({'.txt': 'text/plain;charset=UTF-8'}) + + def do_GET(self): + if not os.path.isfile(os.getcwd() + self.path): + exts = ['html', 'txt'] + for ext in exts: + p = ".".join((self.path, ext)) + if os.path.isfile("".join((os.getcwd(), p))): + self.path = p + break + super().do_GET() + +class ReuseAddrTCPServer(socketserver.TCPServer): + allow_reuse_address = True + +with ReuseAddrTCPServer((ADDR, PORT), HttpRequestHandler) as httpd: + try: + print("serving at port", PORT) + httpd.serve_forever() + except KeyboardInterrupt: + pass + except Exception as e: + logger.exception(e)