Finding messageID of Pub/Sub message triggering Cloud Function

Viewed 655

I'm trying to access messageId of the Pub/Sub message triggering my Golang function. To do so, I'm trying to modify the PubSubMessage struct from the Cloud Functions documentation:

// PubSubMessage is the payload of a Pub/Sub event.
// See the documentation for more details:
// https://cloud.google.com/pubsub/docs/reference/rest/v1/PubsubMessage
type PubSubMessage struct {
        Data []byte `json:"data"`
        MessageId string `json:"messageId"`
}

The function compiles OK but the MessageID value comes empty. Changing the type doesn't help. I wonder if there's a way to get the triggering message Id from within a function. Or maybe that's not passed to functions at all?

1 Answers

In the document you refer,

Event structure

Cloud Functions triggered from a Pub/Sub topic will be sent events conforming to the PubsubMessage type, with the caveat that publishTime and messageId are not directly available in the PubsubMessage. Instead, you can access publishTime and messageId via the event ID and timestamp properties of the event metadata. This metadata is accessible via the context object that is passed to your function when it is invoked.

You can get messageId like this.

import  "cloud.google.com/go/functions/metadata"

func YourFunc(ctx context.Context, m PubSubMessage) error {
    metadata, err := metadata.FromContext(ctx)
    if err != nil {
        // Handle Error
    }
    messageId := metadata.EventID

    // Rest of your code below here.
}
Related