8
8
from .methods import HTTPMethod
9
9
from .request import HTTPRequest
10
10
from .response import HTTPResponse
11
+ from .route import HTTPRoute
11
12
from .status import HTTPStatus
12
13
13
14
class HTTPServer :
@@ -22,7 +23,7 @@ def __init__(self, socket_source: Any) -> None:
22
23
in CircuitPython or the `socket` module in CPython.
23
24
"""
24
25
self ._buffer = bytearray (1024 )
25
- self .routes = {}
26
+ self .route_handlers = {}
26
27
self ._socket_source = socket_source
27
28
self ._sock = None
28
29
self .root_path = "/"
@@ -44,7 +45,7 @@ def route_func(request):
44
45
"""
45
46
46
47
def route_decorator (func : Callable ) -> Callable :
47
- self .routes [ _HTTPRequest (path , method )] = func
48
+ self .route_handlers [ HTTPRoute (path , method )] = func
48
49
return func
49
50
50
51
return route_decorator
@@ -96,12 +97,17 @@ def poll(self):
96
97
97
98
request = HTTPRequest (raw_request = self ._buffer [:length ])
98
99
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.
103
107
elif request .method == HTTPMethod .GET :
104
108
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.
105
111
else :
106
112
response = HTTPResponse (status = HTTPStatus .INTERNAL_SERVER_ERROR )
107
113
0 commit comments