如何在 Go 中创建 AWS Lambda 来处理多个事件

我需要实施 AWS Lambda 处理程序来处理 AWS S3Events 和 SNSEvent,有什么解决方案吗?

How to support more one trigger in AWS Lambda in Golang?

但这对我不起作用。


萧十郎
浏览 122回答 2
2回答

潇湘沐

根据此文档,您可以处理您的自定义事件。因此您可以创建包含 S3Entity 和 SNSEntity 的自定义事件type Record struct {   EventVersion         string           `json:"EventVersion"`   EventSubscriptionArn string           `json:"EventSubscriptionArn"`   EventSource          string           `json:"EventSource"`   SNS                  events.SNSEntity `json:"Sns"`   S3                   events.S3Entity  `json:"s3"`}type Event struct {    Records []Record `json:"Records"`}然后检查事件源func handler(event Event) error {   if len(event.Records) > 0 {    if event.Records[0].EventSource == "aws:sns" {       //Do Something    } else {       //Do Something    }  }  return nil}

慕森王

你可以使用 Go 中的嵌入来解决这个问题import (    "github.com/aws/aws-lambda-go/events"    "github.com/aws/aws-lambda-go/lambda"    "reflect")type Event struct {    events.SQSEvent    events.APIGatewayProxyRequest    //other event type}type Response struct {    events.SQSEventResponse `json:",omitempty"`    events.APIGatewayProxyResponse `json:",omitempty"`   //other response type}func main() {    lambda.Start(eventRouter)}func eventRouter(event Event) (Response, error) {    var response Response    switch {    case reflect.DeepEqual(event.APIGatewayProxyRequest, events.APIGatewayProxyRequest{}):        response.SQSEventResponse = sqsEventHandler(event.SQSEvent)    case reflect.DeepEqual(event.SQSEvent, events.SQSEvent{}):        response.APIGatewayProxyResponse = apiGatewayEventHandler(event.APIGatewayProxyRequest)  //another case for a event handler    }    return response, nil}func sqsEventHandler(sqsEvent events.SQSEvent) events.SQSEventResponse {    //do something with the SQS event }func apiGatewayEventHandler(apiEvent events.APIGatewayProxyRequest) events.APIGatewayProxyResponse {    //do something with the API Gateway event}注意:如果基本事件有一些相同的字段名称,您将需要寻找另一个 DeepEqual 的比较方法实例。
打开App,查看更多内容
随时随地看视频慕课网APP