Warm tip: This article is reproduced from serverfault.com, please click

How to receive publishTime

发布于 2020-11-27 22:10:32

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?

Questioner
Neal S
Viewed
0
guillaume blaquiere 2020-11-28 21:38:35

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

  1. Perform a go get cloud.google.com/go
  2. Use this dependency in your code and get the message metadata from the context
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
}