【问题标题】:查找 Pub/Sub 消息触发 Cloud Function 的 messageID
【发布时间】:2021-12-31 16:20:18
【问题描述】:

我正在尝试访问触发我的 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。或者可能根本没有传递给函数?

【问题讨论】:

    标签: go google-cloud-functions google-cloud-pubsub


    【解决方案1】:

    在您参考的文件中,

    事件结构

    从 Pub/Sub 主题触发的云函数将是 发送符合 PubsubMessage 类型的事件,需要注意的是 publishTime 和 messageId 在 发布订阅消息。相反,您可以通过以下方式访问 publishTime 和 messageId 事件元数据的事件 ID 和时间戳属性。这 元数据可通过传递给您的上下文对象访问 调用时的函数。

    你可以像这样得到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.
    }
    

    【讨论】:

    • 元数据结构中没有 EventId 字段,但可以使用 EventID ??
    • 感谢您的指出。修正了我的答案。
    • TIL 如何做到这一点。再次感谢! ?
    猜你喜欢
    • 2022-01-01
    • 2021-09-09
    • 2020-02-21
    • 2018-06-22
    • 2020-02-03
    • 2018-09-29
    • 2021-02-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多