@@ -8,27 +8,18 @@ class Router(AbstractRouter):
8
8
"""User should never construct Router"""
9
9
10
10
# todo: I may want to change the constructor
11
- def __init__ (self , default_get , default_post ):
11
+ def __init__ (self , default_get ):
12
12
self ._routes = {
13
13
'GET' : {},
14
14
'POST' : {}
15
15
}
16
- self .method_default = {
17
- 'GET' : default_get ,
18
- 'POST' : default_post
19
- }
16
+ self .default_get = default_get
20
17
21
- def _route (self , method : str , route : str , handler ):
22
- assert method in ['GET' , 'POST' ]
18
+ def register (self , method : str , route : str , handler ):
19
+ assert method in ['GET' , 'POST' ] # 这只是目前为了测试而加的限制
23
20
self ._routes [method ][route ] = handler
24
21
25
- def get (self , route : str , handler ):
26
- self ._route ('GET' , route , handler )
27
-
28
- def post (self , route : str , handler ):
29
- self ._route ('POST' , route , handler )
30
-
31
- def match (self , path : str ):
22
+ def find_match (self , path : str ):
32
23
"""
33
24
'user/{userId}' should match 'user/abc'
34
25
userId = abc
@@ -39,11 +30,14 @@ def match(self, path: str):
39
30
# todo: now the problem is how to implement it
40
31
# todo: pattern matching should be independent from :method,
41
32
# todo: but the current implementation doesn't support it. Should improve it later.
33
+ print (self ._routes .values ())
42
34
for routes_of_this_method in self ._routes .values ():
35
+ print (routes_of_this_method )
43
36
for route in routes_of_this_method :
44
37
matched , parameters = self ._match (route , path )
45
38
if matched :
46
39
return route , parameters
40
+ return None , None
47
41
48
42
@classmethod
49
43
def _match (cls , route , path ):
@@ -70,8 +64,23 @@ async def handle_route(self, http: HTTP, stream: Stream):
70
64
path = stream .headers [':path' ].lstrip ('/' )
71
65
method = stream .headers [':method' ]
72
66
73
- route , parameters = self .match (path )
67
+ route , parameters = self .find_match (path )
68
+ print ('app.App.handle_route' , route )
69
+
70
+ # 如果没有任何匹配,就默认为静态文件读取
71
+ if route is None :
72
+ if method == 'GET' :
73
+ print ('GET' )
74
+ handler = self .default_get
75
+ else :
76
+ handler = None
77
+ else :
78
+ handler = self ._routes [method ].get (route , None )
74
79
75
- handler = self ._routes [method ].get (route , self .method_default [method ])
76
80
if handler is not None :
77
- await handler (http , stream , parameters = parameters )
81
+ print ('handle' )
82
+ print (handler )
83
+ await handler (http , stream , parameters )
84
+ else :
85
+ # maybe raise an error?
86
+ raise Exception (path , 'is not a valid request path' )
0 commit comments