Problem with unmarshal an event from eventbridge inside an SQS message in Go lambda function

Viewed 275

I have a lambda that is subscribed to SQS, messages from eventBridge go to SQS

I want to get to two variables from the ECR eventBridge event("repository-name", "image-digest") When everything happens automatically, I mean AWS sends the event to sqs then lambda processes the message well and is able to parse the message and I can get these two variables. But when I want to test it myself and I try to put sample event to the SQS (via AWS console)

This event:

{
    "version": "0",
    "id": "13cde686-328b-6117-af20-0e5566167482",
    "detail-type": "ECR Image Action",
    "source": "aws.ecr",
    "account": "123456789012",
    "time": "2019-11-16T01:54:34Z",
    "region": "us-west-2",
    "resources": [],
    "detail": {
        "result": "SUCCESS",
        "repository-name": "my-repository-name",
        "image-digest": "sha256:7f5b2640fe6fb4f46592dfd3410c4a79dac4f89e4782432e0378abcd1234",
        "action-type": "PUSH",
        "image-tag": "latest"
    }
}

The Golang Unmarshal function cannot parse this message and gets an error invalid character '\\' looking for beginning of object key string

I printed myself the message that is then on the (fmt.Printf("%q", message.Body)) queue and it looks like this:

"\"{\\\"version\\\": \\\"0\\\",\\\"id\\\":\\\"dd783346-7f45-f718-6b64-740a553c2dca\\\",\\\"detail-type\\\":\\\"ECR Image Scan\\\",\\\"source\\\": \\\"aws.ecr\\\",\\\"account\\\": \\\"XXXXX\\\",\\\"time\\\":\\\"2022-04-08T09:50:47Z\\\",\\\"region\\\": \\\"eu-west-1\\\",\\\"resources\\\": [\\\"arn:aws:ecr:eu-west-1:XXXX:repository\\/temp\\/example_app\\\"],\\\"detail\\\": {\\\"scan-status\\\": \\\"COMPLETE\\\",\\\"repository-name\\\": \\\"temp\\/example_app\\\",\\\"image-digest\\\": \\\"sha256:XXXXX\\\",\\\"image-tags\\\": [\\\"0.0.3\\\"],\\\"finding-severity-counts\\\": {\\\"MEDIUM\\\": 12,=\\\"LOW\\\": 2}}}\""

The Go lambda function code:

package main

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

    "github.com/aws/aws-lambda-go/events"
    "github.com/aws/aws-lambda-go/lambda"
)

func HandleRequest(ctx context.Context, sqsEvent events.SQSEvent) error {
    for _, message := range sqsEvent.Records {
        fmt.Printf("%q", message.Body)
        eventBridgeEvent := events.ECRScanEvent{}
        err := json.Unmarshal([]byte(message.Body), &eventBridgeEvent)

        if err != nil {
            fmt.Println(err.Error())
            return err
        }

        fmt.Println(eventBridgeEvent.Detail.RepositoryName)
        fmt.Println(eventBridgeEvent.Detail.ImageDigest)
    }

    return nil
}

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

I'm from the NodeJs world and there the JSON.parse() function eliminates these types of errors. I don't know why this happens here and how can I prevent this type of error, how to get rid of this error?

0 Answers
Related