为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
萧十郎 2023-06-26 15:47:31
我需要实施 AWS Lambda 处理程序来处理 AWS S3Events 和 SNSEvent,有什么解决方案吗?How to support more one trigger in AWS Lambda in Golang?但这对我不起作用。
查看完整描述

2 回答

?
潇湘沐

TA贡献1816条经验 获得超6个赞

根据此文档,您可以处理您的自定义事件。因此您可以创建包含 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

}


查看完整回答
反对 回复 2023-06-26
?
慕森王

TA贡献1777条经验 获得超3个赞

你可以使用 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 的比较方法实例。


查看完整回答
反对 回复 2023-06-26
  • 2 回答
  • 0 关注
  • 120 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信