gpt4 book ai didi

go - 查找触发 Cloud Function 的 Pub/Sub 消息的 messageID

转载 作者:行者123 更新时间:2023-12-02 18:26:36 26 4
gpt4 key购买 nike

我正在尝试访问触发我的 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 besent events conforming to the PubsubMessage type, with the caveat thatpublishTime and messageId are not directly available in thePubsubMessage. Instead, you can access publishTime and messageId viathe event ID and timestamp properties of the event metadata. Thismetadata is accessible via the context object that is passed to yourfunction 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.
}

关于go - 查找触发 Cloud Function 的 Pub/Sub 消息的 messageID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70059453/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com