forked from aws-powertools/powertools-lambda-python
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcreate_own_router_app.py
37 lines (25 loc) · 1 KB
/
create_own_router_app.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
import json
def hello_name(event, **kargs):
username = event["pathParameters"]["name"]
return {"statusCode": 200, "body": json.dumps({"message": f"hello {username}!"})}
def hello(**kargs):
return {"statusCode": 200, "body": json.dumps({"message": "hello unknown!"})}
class Router:
def __init__(self):
self.routes = {}
def set(self, path, method, handler):
self.routes[f"{path}-{method}"] = handler
def get(self, path, method):
try:
route = self.routes[f"{path}-{method}"]
except KeyError:
raise RuntimeError(f"Cannot route request to the correct method. path={path}, method={method}")
return route
router = Router()
router.set(path="/hello", method="GET", handler=hello)
router.set(path="/hello/{name}", method="GET", handler=hello_name)
def lambda_handler(event, context):
path = event["resource"]
http_method = event["httpMethod"]
method = router.get(path=path, method=http_method)
return method(event=event)