3

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.

1 Answer 1

4

fieldmaskpb.FieldMask type provides someuseful methods like IsValid and Normalize.

The append method looks like can be used in your case of merging.

There are some great repo to deal with field mask, 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.