查找 Pub/Sub 条消息的消息 ID 触发 Cloud Function
Finding messageID of Pub/Sub message triggering Cloud Function
我正在尝试访问触发我的 Golang 函数的 Pub/Sub 消息的 messageId。为此,我尝试从 Cloud Functions documentation:
修改 PubSubMessage 结构
// 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"`
}
函数编译正常,但 MessageID 值为空。更改类型没有帮助。
我想知道是否有办法从函数中获取触发消息 ID。或者可能根本没有传递给函数?
在您引用的文档中,
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.
你可以这样得到messageId
。
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.
}
我正在尝试访问触发我的 Golang 函数的 Pub/Sub 消息的 messageId。为此,我尝试从 Cloud Functions documentation:
修改 PubSubMessage 结构// 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"`
}
函数编译正常,但 MessageID 值为空。更改类型没有帮助。 我想知道是否有办法从函数中获取触发消息 ID。或者可能根本没有传递给函数?
在您引用的文档中,
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.
你可以这样得到messageId
。
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.
}