The prerequisite is Golang version 1.19. And I have checked similar questions in the past.
How to create AWS Lambda in Go to handle multiple events
How to support more than one trigger in AWS Lambda in Golang?
I am posting the same question because I felt the response time was old and not appropriate.
The code is written on the assumption that requests to Lambda come from SNS and API Gateway.
package main
import (
"fmt"
"reflect"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
)
type TestInterface interface {
events.APIGatewayProxyRequest | events.SNSEvent
}
func mixHandler[T TestInterface](event T) {
switch (interface{})(event).(type) {
case events.SNSEvent:
fmt.Println("SNS request")
logStr := fmt.Sprintf("%+v", event)
fmt.Println(logStr)
case events.APIGatewayProxyRequest:
fmt.Println("API Gateway request")
logStr := fmt.Sprintf("%+v", event)
fmt.Println(logStr)
default:
fmt.Println("Unknow request")
logStr := fmt.Sprintf("%+v", event)
fmt.Println(logStr)
valueType := reflect.TypeOf(event)
fmt.Println(valueType)
}
}
func main() {
lambda.Start(mixHandler)
}
I thought this was OK, and when I used Execute, the following error occurred.
cannot use generic function mixHandler without instantiation
I asked a separate question, but you said it is currently impossible to use a generics type, so is there any other way to handle multiple triggers?