add custom python3 'serve' script based on http.server
authorAmin Bandali <bandali@gnu.org>
Fri, 5 Nov 2021 05:14:44 +0000 (01:14 -0400)
committerAmin Bandali <bandali@gnu.org>
Fri, 5 Nov 2021 05:14:44 +0000 (01:14 -0400)
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).

serve [new file with mode: 0755]

diff --git a/serve b/serve
new file mode 100755 (executable)
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)