英文:
Finding messageID of Pub/Sub message triggering Cloud Function
问题
我正在尝试访问触发我的 Golang 函数的 Pub/Sub 消息的 messageId。为了做到这一点,我正在尝试修改来自Cloud Functions 文档的 PubSubMessage 结构体:
// PubSubMessage 是 Pub/Sub 事件的有效载荷。
// 更多细节请参阅文档:
// https://cloud.google.com/pubsub/docs/reference/rest/v1/PubsubMessage
type PubSubMessage struct {
Data []byte `json:"data"`
MessageId string `json:"messageId"`
}
函数编译没有问题,但 MessageID 的值为空。更改类型也没有帮助。
我想知道是否有一种方法可以从函数内部获取触发消息的 ID。或者也许根本不会将其传递给函数?
英文:
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
得分: 5
在你提到的文档中,
事件结构
从 Pub/Sub 主题触发的云函数将收到符合 PubsubMessage 类型的事件,但需要注意的是,publishTime 和 messageId 在 PubsubMessage 中不直接可用。相反,您可以通过事件元数据的事件 ID 和时间戳属性来访问 publishTime 和 messageId。此元数据可以通过传递给函数的上下文对象来访问。
您可以按照以下方式获取 messageId
。
import "cloud.google.com/go/functions/metadata"
func YourFunc(ctx context.Context, m PubSubMessage) error {
metadata, err := metadata.FromContext(ctx)
if err != nil {
// 处理错误
}
messageId := metadata.EventID
// 在此处编写您的其余代码。
}
英文:
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.
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论