rearrange many of the pages/files for better organization
[~bandali/bndl.org] / serve
CommitLineData
1742e668
AB
1#!/usr/bin/env python3
2
3# Copyright (c) 2021 bandali
4#
5# Copying and distribution of this file, with or without modification,
6# are permitted in any medium without royalty provided the copyright
7# notice and this notice are preserved. This file is offered as-is,
8# without any warranty.
9
10import os
11from http.server import SimpleHTTPRequestHandler
12import socketserver
13
14try:
15 PORT = int(os.getenv('PORT', 8000))
16except ValueError:
17 print('PORT must be in integer')
18 exit(1)
19
20ADDR = os.getenv('ADDR', '127.0.0.1')
21
22class HttpRequestHandler(SimpleHTTPRequestHandler):
23 extensions_map = dict(SimpleHTTPRequestHandler.extensions_map)
24 extensions_map.update({'': 'text/plain;charset=UTF-8'})
25 extensions_map.update({'.txt': 'text/plain;charset=UTF-8'})
26
27 def do_GET(self):
28 if not os.path.isfile(os.getcwd() + self.path):
29 exts = ['html', 'txt']
30 for ext in exts:
31 p = ".".join((self.path, ext))
32 if os.path.isfile("".join((os.getcwd(), p))):
33 self.path = p
34 break
35 super().do_GET()
36
37class ReuseAddrTCPServer(socketserver.TCPServer):
38 allow_reuse_address = True
39
40with ReuseAddrTCPServer((ADDR, PORT), HttpRequestHandler) as httpd:
41 try:
42 print("serving at port", PORT)
43 httpd.serve_forever()
44 except KeyboardInterrupt:
45 pass
46 except Exception as e:
47 logger.exception(e)