buranun/server.py

51 lines
1.2 KiB
Python
Raw Normal View History

2018-03-18 19:33:16 +00:00
import http.server
import urllib.parse
2018-03-31 21:12:40 +00:00
import generate_html
2018-03-18 19:33:16 +00:00
class HTTPRequestHandler(http.server.BaseHTTPRequestHandler):
server_version = 'Buranun/0.0'
protocol_version = 'HTTP/1.1'
2018-03-31 21:12:40 +00:00
def __send_html(self, html, *, status_code = 200):
encoded = html.encode('utf-8')
2018-03-18 19:33:16 +00:00
length = len(encoded)
2018-03-31 21:12:40 +00:00
self.send_response(status_code)
self.send_header('Content-Type', 'text/html; charset=utf-8')
2018-03-18 19:33:16 +00:00
self.send_header('Content-Length', length)
self.end_headers()
self.wfile.write(encoded)
2018-03-31 21:12:40 +00:00
def __send_404(self, path):
html = generate_html.error_404(path)
self.__send_html(html, status_code = 404)
2018-03-18 19:33:16 +00:00
def do_GET(self):
path = urllib.parse.unquote(self.path)
2018-03-31 21:12:40 +00:00
path_components = [component for component in path.split('/') if component != '']
if len(path_components) == 0:
# Path of format / → index
html = generate_html.index()
self.__send_html(html)
elif len(path_components) == 1:
# Path of format /foo/ → board index
board_name = path_components[0]
html = generate_html.board(board_name)
self.__send_html(html)
else:
# Path not understood, send 404
self.__send_404(path)
2018-03-18 19:33:16 +00:00
def main():
httpd = http.server.HTTPServer(('', 4000), HTTPRequestHandler)
2018-03-18 19:33:16 +00:00
httpd.serve_forever()
if __name__ == '__main__':
main()