2

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?

How to use Golang generics types in AWS Lambda

John Rotenstein
  • 241,921
  • 22
  • 380
  • 470
kyoshida
  • 191
  • 8
  • 1
    Since `events.APIGatewayProxyRequest` and `events.SNSEvent` don't have overlapped fields, the [embedding approach](https://stackoverflow.com/a/71117911/1369400) should work for you. But instead of using `reflect.DeepEqual`, I think it's better to check the fields to determine the event type. For example, if `len(event.Resource) > 0`, then the type is `events.APIGatewayProxyRequest`. Have you tried this approach? – Zeke Lu Jun 05 '23 at 03:26
  • I have tried the embedding approach and it works! The actual code presented was to enter the condition when the value was empty, so I changed it to a negative expression and implemented it. Thanks! – kyoshida Jun 08 '23 at 08:28

0 Answers0