#!/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)