-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp_server.py
54 lines (41 loc) · 1.76 KB
/
http_server.py
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import mimetypes
import os
from constants import DEFAULT_HEADERS, STATUS_CODES
from http_request import HTTPRequest
from tcp_server import TCPServer
class HTTPServer(TCPServer):
def handle_request(self, data):
request = HTTPRequest(data)
try:
handler = getattr(self, f"handle_{request.method}", None)
response = handler(request) if handler else self.error_501()
except Exception as e:
response = self.error_500()
return response.encode() if isinstance(response, str) else response
def handle_GET(self, request):
path = request.uri.lstrip("/") or "index.html"
if os.path.exists(path):
return self.serve_file(path)
return self.error_404()
def serve_file(self, path):
content_type, _ = mimetypes.guess_type(path)
headers = {**DEFAULT_HEADERS, "Content-Type": content_type or "text/html"}
try:
with open(path, "rb") as f:
return self.build_response(200, headers, f.read())
except IOError:
return self.error_500()
def build_response(self, status_code, headers, body):
status_line = f"HTTP/1.1 {status_code} {STATUS_CODES[status_code]}\r\n"
header_lines = "".join(f"{k}: {v}\r\n" for k, v in headers.items())
return b"".join([status_line.encode(), header_lines.encode(), b"\r\n", body])
def error_404(self):
return self.build_response(404, DEFAULT_HEADERS, b"<h1>404 Not Found</h1>")
def error_501(self):
return self.build_response(
501, DEFAULT_HEADERS, b"<h1>501 Not Implemented</h1>"
)
def error_500(self):
return self.build_response(
500, DEFAULT_HEADERS, b"<h1>500 Internal Server Error</h1>"
)