AWS SAM Local和Serverless-offline都是用于在本地环境中模拟和测试AWS Lambda函数的工具。这两个工具的实现方式有所不同。以下是两种工具的用法和示例代码:
AWS SAM Local:
sam local start-api
示例代码:
// SAM模板
Resources: SampleFunction: Type: AWS::Serverless::Function Properties: Handler: index.handler Runtime: nodejs12.x CodeUri: . Events: GetEvent: Type: Api Properties: Path: /sample Method: get
// Lambda函数代码
exports.handler = async (event) => { return { statusCode: 200, body: JSON.stringify({ message: 'Hello from AWS Lambda function', }), }; };
Serverless-offline:
sls offline
示例代码:
service: sample-service
plugins:
provider: name: aws runtime: nodejs12.x
functions: sample: handler: handler.handler events: - http: path: /sample method: get
exports.handler = async (event) => { return { statusCode: 200, body: JSON.stringify({ message: 'Hello from AWS Lambda function', }), }; };