简体   繁体   中英

How to use protocol buffer FieldMask in Go

Python Generated Code lists Well Known Types , but there is no equivalent in Go Generated Code . I assume if there was, it would document this package google.golang.org/protobuf/types/known .

Specifically, I was looking for documentation on 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 ).

Question

The Python implementation of FieldMask provides a MergeMessage function that merges fields specified in FieldMask from source to destination. This is really useful in API update operations because you can easily merge 2 proto messages while honoring the FieldMask :

# 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? If not, how should proto messages be merged using a FieldMask ? Is there a reference implementation or example I could follow? I couldn't find any use of FieldMask in grpc-go/examples/ .

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.

I think it's developer's job to deal with the protobuf FieldMask in go.

fieldmaskpb.FieldMask type only provides IsValid and Normalize methods.

There are some great repo for this problem, fieldmask-utils , and fmutils .

Based on my understanding, after you get the FieldMask value, which is a []string :

  1. with go's v1 api, you need to use reflect on the struct (which converted from pb message) or use a map[string]interface{} (converted from pb message) to deal with the FieldMask
  2. or with go's v2 api, it becomes easier, as for the reflect api on proto.Message . Check the code

You can go for more code details in the above repo to help you write your own code related to FieldMask .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM