首页 > 解决方案 > 在golang谷歌云后端功能中获取参数

问题描述

在我的 Go Google Cloud 后台功能中,我想从我的 Firestore 事件中访问参数。

https://cloud.google.com/functions/docs/writing/background#functions_background_parameters-go 指出两个对象 -ctx并被Event传递到后台函数入口点。 Event应该能够与将收到的特定事件的 json.Unmarshal() 一起使用。

有了这些知识,https: //cloud.google.com/functions/docs/calling/cloud-firestore 将事件结构记录为

{
    "oldValue": { // Update and Delete operations only
        A Document object containing a pre-operation document snapshot
    },
    "updateMask": { // Update operations only
        A DocumentMask object that lists changed fields.
    },
    "value": {
        // A Document object containing a post-operation document snapshot
    }
}

但它也指出Wildcard matches are extracted from document paths and stored in event.params. You can define as many wildcards as you like to substitute explicit collection or document IDs.

所以根据上面,我可能应该添加类似的东西

Params map[string]string `json:"params"`

到我用于解码事件的结构。不幸的是,这不起作用。任何关于如何从 Golang 后台函数中的 firestore 事件访问这些命名参数的提示都将非常受欢迎。

标签: gogoogle-cloud-firestoregoogle-cloud-functions

解决方案


您可以获取事件完整路径,然后将其'/documents'拆分并再次拆分以查找参数值:

path := strings.Split(e.Value.Name, "/documents/")[1]
parts := strings.Split(path, "/")

文档不是很清楚,但似乎这是从 golang 访问参数的唯一方法。


推荐阅读