[英]How to use protocol buffer FieldMask in Go
Python Generated Code lists Well Known Types , but there is no equivalent in Go Generated Code . Python 生成的代码列出了众所周知的类型,但Go 生成的代码中没有等效的类型。 I assume if there was, it would document this package google.golang.org/protobuf/types/known .
我假设如果有,它会记录这个包google.golang.org/protobuf/types/known 。
Specifically, I was looking for documentation on FieldMask
.具体来说,我正在寻找有关
FieldMask
文档。 While it's completely absent on Go Generated Code , I did find it on go.dev ( https://pkg.go.dev/google.golang.org/protobuf/types/known/fieldmaskpb ).虽然它在Go Generated Code上完全不存在,但我确实在go.dev ( https://pkg.go.dev/google.golang.org/protobuf/types/known/fieldmaskpb ) 上找到了它。
Question题
The Python implementation of FieldMask provides a MergeMessage
function that merges fields specified in FieldMask
from source to destination. FieldMask的 Python 实现提供了一个
MergeMessage
函数,该函数将FieldMask
指定的FieldMask
从源合并到目标。 This is really useful in API update operations because you can easily merge 2 proto messages while honoring the FieldMask
:这在API 更新操作中非常有用,因为您可以在遵守
FieldMask
同时轻松合并 2 条 proto 消息:
# get field mask and message from request
updated_message = request.message
field_mask = request.mask
# load original message from database
original_message = read_from_db(request.id)
# source, destination
field_mask.MergeMessage(updated_message, original_message)
# original_message is now updated according to the field mask
Is there an equivalent convenience function in Go? Go 中是否有等效的便利功能? If not, how should proto messages be merged using a
FieldMask
?如果没有,应该如何使用
FieldMask
合并原始消息? Is there a reference implementation or example I could follow?是否有我可以遵循的参考实现或示例? I couldn't find any use of
FieldMask
in grpc-go/examples/ .我在grpc-go/examples/ 中找不到任何
FieldMask
的用途。
While there is a proto Merge function , it merges all fields and there is no way to incorporate a FieldMask
to merge only specific fields.虽然有一个 proto Merge 函数,但它合并所有字段,并且无法合并
FieldMask
以仅合并特定字段。
I think it's developer's job to deal with the protobuf FieldMask
in go.我认为在 go 中处理 protobuf
FieldMask
是开发人员的工作。
fieldmaskpb.FieldMask
type only provides IsValid
and Normalize
methods. fieldmaskpb.FieldMask
类型仅提供IsValid
和Normalize
方法。
There are some great repo for this problem, fieldmask-utils , and fmutils .这个问题有一些很好的 repo, fieldmask-utils和fmutils 。
Based on my understanding, after you get the FieldMask
value, which is a []string
:根据我的理解,在获得
FieldMask
值后,它是一个[]string
:
reflect
on the struct
(which converted from pb message) or use a map[string]interface{}
(converted from pb message) to deal with the FieldMask
reflect
struct
(从 pb 消息转换而来)或使用map[string]interface{}
(从 pb 消息转换)来处理FieldMask
proto.Message
.proto.Message
上的反射 api。 Check the codeYou can go for more code details in the above repo to help you write your own code related to FieldMask
.您可以在上述 repo 中查看更多代码详细信息,以帮助您编写自己的与
FieldMask
相关的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.