summaryrefslogtreecommitdiff
path: root/serve-http
blob: 6d69f057c06586c7d63d0b151567e0fd9a66bffd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#!/usr/bin/env python3
"""serve the website over HTTP."""

from os import path
import argparse
import http.server
import socketserver

# https://docs.python.org/3/library/http.server.html


class Handler(http.server.BaseHTTPRequestHandler):
    def do_GET(self):
        resource = f'build/{self.path}.html'
        if self.path == '/':
            resource = 'build/index.html'

        if path.isfile(resource):
            self.send_response(200)
            self.send_header('Content-type', 'text/html')
            self.end_headers()
            with open(resource, mode='rb') as f:
                self.wfile.write(f.read())
        else:
            self.send_response(404)
            self.end_headers()
            self.wfile.write(f'unknown path: {self.path}'.encode())


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--port', default=8080, type=int,
                        help='port to listen on.')
    args = parser.parse_args()

    with socketserver.TCPServer(('127.0.0.1', args.port), Handler) as httpd:
        print('http://localhost:' + str(args.port))
        httpd.serve_forever()