Skip to content

Commit

Permalink
feat: allow Lambda handler be triggered by SQS and API Gateway
Browse files Browse the repository at this point in the history
  • Loading branch information
soerenschneider committed Jul 24, 2024
1 parent ae321ab commit 087319a
Showing 1 changed file with 33 additions and 1 deletion.
34 changes: 33 additions & 1 deletion cmd/server/server_lambda.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@
package main

import (
"context"
"encoding/json"
"fmt"

"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
Expand Down Expand Up @@ -36,7 +38,21 @@ func init() {
}
}

func handler(request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
func handleSQSEvent(_ context.Context, event events.SQSEvent) error {
for _, message := range event.Records {
payload := common.UpdateRecordRequest{}
if err := json.Unmarshal([]byte(message.Body), &payload); err != nil {
return err
}

if err := dyndnsServer.HandlePropagateRequest(payload); err != nil {
return err
}
}
return nil
}

func handleAPIGatewayRequest(_ context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
payload := common.UpdateRecordRequest{}
if err := json.Unmarshal([]byte(request.Body), &payload); err != nil {
return events.APIGatewayProxyResponse{
Expand All @@ -56,6 +72,22 @@ func handler(request events.APIGatewayProxyRequest) (events.APIGatewayProxyRespo
}, nil
}

func handler(ctx context.Context, rawEvent json.RawMessage) (interface{}, error) {
// Try to parse as APIGatewayProxyRequest
var apiGatewayRequest events.APIGatewayProxyRequest
if err := json.Unmarshal(rawEvent, &apiGatewayRequest); err == nil && apiGatewayRequest.HTTPMethod != "" {
return handleAPIGatewayRequest(ctx, apiGatewayRequest)
}

// Try to parse as SQSEvent
var sqsEvent events.SQSEvent
if err := json.Unmarshal(rawEvent, &sqsEvent); err == nil && len(sqsEvent.Records) > 0 {
return nil, handleSQSEvent(ctx, sqsEvent)
}

return nil, fmt.Errorf("unsupported event type")
}

func main() {
lambda.Start(handler)
}

0 comments on commit 087319a

Please sign in to comment.