mirror of
https://github.com/swift-server/swift-aws-lambda-runtime.git
synced 2026-05-03 07:22:27 +00:00
023b8fe526
See issue #536 All the examples are now depending on the runtime library located at `../..`. The `Package.swift` files contain a commented line with the `.package` to use when user wants to fetch the runtime from GitHub. --------- Co-authored-by: Sebastien Stormacq <stormacq@amazon.lu>
Multi-Source API Example
This example demonstrates a Lambda function that handles requests from both Application Load Balancer (ALB) and API Gateway V2 by accepting a raw ByteBuffer and decoding the appropriate event type.
Overview
The Lambda handler receives events as ByteBuffer and attempts to decode them as either:
ALBTargetGroupRequest- for requests from Application Load BalancerAPIGatewayV2Request- for requests from API Gateway V2
Based on the successfully decoded type, it returns an appropriate response.
Building
swift package archive --allow-network-connections docker
Deploying
Deploy using SAM:
sam deploy \
--resolve-s3 \
--template-file template.yaml \
--stack-name MultiSourceAPI \
--capabilities CAPABILITY_IAM
Testing
After deployment, SAM will output two URLs:
Test API Gateway V2:
curl https://<api-id>.execute-api.<region>.amazonaws.com/apigw/test
Expected response:
{"source":"APIGatewayV2","path":"/apigw/test"}
Test ALB:
curl http://<alb-dns-name>/alb/test
Expected response:
{"source":"ALB","path":"/alb/test"}
How It Works
The handler uses Swift's type-safe decoding to determine the event source:
- Receives raw
ByteBufferevent - Attempts to decode as
ALBTargetGroupRequest - If that fails, attempts to decode as
APIGatewayV2Request - Returns appropriate response based on the decoded type
- Throws error if neither decoding succeeds
This pattern is useful when a single Lambda function needs to handle requests from multiple sources.