在AWS Lambda代理集成中,有时需要将请求路径中的资源剥离出来,以便于更好地处理请求。这可以通过使用AWS API Gateway提供的Lambda代理集成来实现。以下是示例代码:
在Lambda函数中,可以通过event对象访问请求路径中的参数,例如:
def handler(event, context):
resource = event['pathParameters']['resource']
# do something with the resource variable
API Gateway还提供了一个特殊的映射模板,用于将请求路径中的资源剥离出来。在API Gateway中选择Lambda代理集成时,可以在'HTTP请求”选项卡中找到'映射模板”下拉菜单。
选择'重写URI”选项并在模板中输入以下代码:
{
"resourcePath": "$context.resourcePath",
"httpMethod": "$context.httpMethod",
"stage": "$context.stage",
"identity": {
"sourceIp": "$context.identity.sourceIp",
"userAgent": "$context.identity.userAgent"
},
"params": {
"resource": "$input.params('resource')"
}
}
在Lambda函数中可以使用以下代码来访问资源:
def handler(event, context):
resource = event['params']['resource']
# do something with the resource variable