88from .methods import HTTPMethod
99from .request import HTTPRequest
1010from .response import HTTPResponse
11+ from .route import HTTPRoute
1112from .status import HTTPStatus
1213
1314class HTTPServer :
@@ -22,7 +23,7 @@ def __init__(self, socket_source: Any) -> None:
2223 in CircuitPython or the `socket` module in CPython.
2324 """
2425 self ._buffer = bytearray (1024 )
25- self .routes = {}
26+ self .route_handlers = {}
2627 self ._socket_source = socket_source
2728 self ._sock = None
2829 self .root_path = "/"
@@ -44,7 +45,7 @@ def route_func(request):
4445 """
4546
4647 def route_decorator (func : Callable ) -> Callable :
47- self .routes [ _HTTPRequest (path , method )] = func
48+ self .route_handlers [ HTTPRoute (path , method )] = func
4849 return func
4950
5051 return route_decorator
@@ -96,12 +97,17 @@ def poll(self):
9697
9798 request = HTTPRequest (raw_request = self ._buffer [:length ])
9899
99- # If a route exists for this request, call it. Otherwise try to serve a file.
100- route = self .routes .get (request , None )
101- if route :
102- response = route (request )
100+ handler = self .route_handlers .get (HTTPRoute (request .path , request .method ), None )
101+
102+ # If a handler for route exists, call it.
103+ if handler :
104+ response = handler (request )
105+
106+ # If no handler exists and request method is GET, try to serve a file.
103107 elif request .method == HTTPMethod .GET :
104108 response = HTTPResponse (filename = request .path , root = self .root_path )
109+
110+ # If no handler exists and request method is not GET, return 500 Internal Server Error.
105111 else :
106112 response = HTTPResponse (status = HTTPStatus .INTERNAL_SERVER_ERROR )
107113
0 commit comments