I have a GC function in Go, It is triggered by pubsub push subscription to a topic. I am trying to receive the publishTime and it does not appear populated.
The specs say string (Timestamp format), however, that field in my model is empty. Every other piece of information is populated except publishTime.
type PubSubMessageModel struct {
Data []byte `json:"data"`
Attributes map[string]string `json:"attributes"`
PublishTime string `json:"publishTime"`
}
Simply trying to log the property;
log.Info().Msgf("Publish Time is - %s\n", m.PublishTime)
results in an empty string:
Publish Time is -
Any suggestions?
It's not very well documented, but it is.
The event structure is different when you have a push to the function directly compare to a push Subscription with a HTTP triggered function.
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.
In the background context description, in Go, there is an explanation of the package to use (functions/metadata) to get the context values
Here how to achieve this
go get cloud.google.com/go
import (
"cloud.google.com/go/functions/metadata"
"context"
"log"
)
type PubSubMessage struct {
Data []byte `json:"data"`
}
// HelloPubSub consumes a Pub/Sub message.
func HelloPubSub(ctx context.Context, m PubSubMessage) error {
meta,err := metadata.FromContext(ctx)
if err != nil {
log.Println(err)
return err
}
log.Printf("publishTime, %s", meta.Timestamp)
log.Printf("messageId, %s", meta.EventID)
log.Printf("Type, %s", meta.EventType)
log.Printf("Resource, %s", meta.Resource)
return nil
}