AWS: special case API gateway to always return gzipped data to avoid binary/base64 unwanted behavior.

This commit is contained in:
Brandon Liu
2022-07-27 00:36:46 +08:00
parent 87c47a23fb
commit c161c01322

View File

@@ -35,7 +35,9 @@ def get_object_bytes(key, offset, length):
# Does not work with CloudFront events/Lambda@Edge; see README # Does not work with CloudFront events/Lambda@Edge; see README
def lambda_handler(event, context): def lambda_handler(event, context):
path = None path = None
is_api_gateway = False
if event.get("pathParameters"): if event.get("pathParameters"):
is_api_gateway = True
# API Gateway (HTTP or REST) # API Gateway (HTTP or REST)
if "proxy" in event["pathParameters"]: if "proxy" in event["pathParameters"]:
path = "/" + event["pathParameters"]["proxy"] path = "/" + event["pathParameters"]["proxy"]
@@ -75,15 +77,22 @@ def lambda_handler(event, context):
else: else:
raise e raise e
# CloudFront requires decompressed responses from lambda headers = {"Content-Type": "application/protobuf"}
# in order to implement the Compressed CacheOptimized policy correctly
# as well as Brotli support
if reader.header().metadata.get("compression") == "gzip": if reader.header().metadata.get("compression") == "gzip":
tile_data = gzip.decompress(tile_data) if is_api_gateway:
# API Gateway requires a compressed response to correctly return binary data
# instead of base64
headers["Content-Encoding"] = "gzip"
else:
# CloudFront requires decompressed responses from lambda
# in order to implement the Compressed CacheOptimized policy correctly
# as well as Brotli support
tile_data = gzip.decompress(tile_data)
return { return {
"statusCode": 200, "statusCode": 200,
"body": base64.b64encode(tile_data), "body": base64.b64encode(tile_data),
"isBase64Encoded": True, "isBase64Encoded": True,
"headers": {"Content-Type": "application/protobuf"}, "headers": headers,
} }