【发布时间】:2021-10-18 01:26:49
【问题描述】:
我正在使用 URL 查询字符串来调试我的 viewer-request 和 viewer-response lambda@edge 函数,方法是将 event 作为 JSON 返回到前端(仅供参考,以便我可以检查某些事物的存在/不存在通过外部监控工具)。
这适用于 viewer-request:如果我转到 https://example.org/?debug_viewer_request_event,我会得到 viewer-request 事件的 JSON:
import json
def lambda_handler(event, context):
request = event["Records"][0]["cf"]["request"]
if "debug_viewer_request_event" in request["querystring"]:
response = {
"status": "200",
"statusDescription": "OK",
"headers": {
"cache-control": [
{
"key": "Cache-Control",
"value": "no-cache"
}
],
"content-type": [
{
"key": "Content-Type",
"value": "application/json"
}
]
},
"body": json.dumps(event)
}
return response
# rest of viewer-request logic...
使用 cURL 进行测试:
curl -i https://example.org/?debug_viewer_request_event
HTTP/2 200
content-type: application/json
content-length: 854
server: CloudFront
date: Mon, 26 Apr 2021 06:05:28 GMT
cache-control: no-cache
x-cache: LambdaGeneratedResponse from cloudfront
via: 1.1 xxxxxxxxxxx.cloudfront.net (CloudFront)
x-amz-cf-pop: AMS50-C1
x-amz-cf-id: pU0ItvQA1-r5v3yR1Dl6Z3VpPW_EuuUCHhnOD60uLhng...
{"Records": [{"cf": {"config": {"distributionDomainName": "xxxxxxx.cloudfront.net", "distributionId": "xxxxxxx", "eventType": "viewer-request", "requestId": "pU0ItvQA1-r5v3yR1Dl6Z3VpPW_EuuUCHhnOD60uLhng...
但是,当我对 viewer-response 执行相同操作时,我会收到 502 错误:
- 除了
debug_viewer_request_event是debug_viewer_response_event之外,代码相同 - 如果我不包含调试查询字符串,则响应为
200 OK,所以我知道总体上两个 lambda 都可以正常工作(viewer-response的调试除外)
这是 cURL 输出:
curl -i https://example.org/?debug_viewer_response_event
HTTP/2 502
content-type: text/html
content-length: 1013
server: CloudFront
date: Mon, 26 Apr 2021 06:07:39 GMT
x-cache: LambdaValidationError from cloudfront
via: 1.1 xxxxxxxxx.cloudfront.net (CloudFront)
x-amz-cf-pop: AMS50-C1
x-amz-cf-id: NqXQ-FFEsIX-fEt8IvlHFTYoQdrZSGPScq1H-KNwVWR0-xxxxxx
The Lambda function result failed validation: The function tried to add, delete, or change a read-only header
如果我查看at the docs,“CloudFront 查看器响应事件的只读标头” 的列表是:
- 内容编码
- 内容长度
- 传输编码
- 警告
- 通过
据我所见,我并没有直接更改任何这些标头,但我猜是因为我正在修改响应,所以像 Content-Length 这样的标头已被修改
问:有没有办法将 viewer-response 事件以 JSON 格式返回到前端进行调试,还是因为无法更改 Content-Length 而根本不可能?
【问题讨论】:
标签: json debugging aws-lambda aws-lambda-edge