package runtimeimport (field_mask)func getFieldByName( protoreflect.FieldDescriptors, string) protoreflect.FieldDescriptor { := .ByName(protoreflect.Name())if != nil {return }return .ByJSONName()}// FieldMaskFromRequestBody creates a FieldMask printing all complete paths from the JSON body.func ( io.Reader, proto.Message) (*field_mask.FieldMask, error) { := &field_mask.FieldMask{}varinterface{}if := json.NewDecoder().Decode(&); != nil {iferrors.Is(, io.EOF) {return , nil }returnnil, } := []fieldMaskPathItem{{node: , msg: .ProtoReflect()}}forlen() > 0 {// dequeue an item := [0] = [1:] , := .node.(map[string]interface{})switch {case && len() > 0:// if the item is an object, then enqueue all of its childrenfor , := range {if .msg == nil {returnnil, errors.New("JSON structure did not match request type") } := getFieldByName(.msg.Descriptor().Fields(), )if == nil {returnnil, fmt.Errorf("could not find field %q in %q", , .msg.Descriptor().FullName()) }ifisDynamicProtoMessage(.Message()) {for , := rangebuildPathsBlindly(string(.FullName().Name()), ) { := if .path != "" { = .path + "." + } = append(, fieldMaskPathItem{path: }) }continue }ifisProtobufAnyMessage(.Message()) && !.IsList() { , := .(map[string]interface{})if , := ["@type"]; ! {returnnil, fmt.Errorf("could not find field @type in %q in message %q", , .msg.Descriptor().FullName()) } := string(.FullName().Name())if .path != "" { = .path + "." + } = append(, fieldMaskPathItem{path: })continue } := fieldMaskPathItem{node: , }if .path == "" { .path = string(.FullName().Name()) } else { .path = .path + "." + string(.FullName().Name()) }switch {case .IsList(), .IsMap():// As per: https://github.com/protocolbuffers/protobuf/blob/master/src/google/protobuf/field_mask.proto#L85-L86 // Do not recurse into repeated fields. The repeated field goes on the end of the path and we stop. .Paths = append(.Paths, .path)case .Message() != nil: .msg = .msg.Get().Message()fallthroughdefault: = append(, ) } }caselen(.path) > 0:// otherwise, it's a leaf node (an empty object counts as one) so // print its path. The root has no path: an empty body such as {} // sets nothing, and an empty path is not a valid FieldMask path. .Paths = append(.Paths, .path) } }// Sort for deterministic output in the presence // of repeated fields.sort.Strings(.Paths)return , nil}func isProtobufAnyMessage( protoreflect.MessageDescriptor) bool {return != nil && (.FullName() == "google.protobuf.Any")}func isDynamicProtoMessage( protoreflect.MessageDescriptor) bool {return != nil && (.FullName() == "google.protobuf.Struct" || .FullName() == "google.protobuf.Value")}// buildPathsBlindly does not attempt to match proto field names to the// json value keys. Instead it relies completely on the structure of// the unmarshalled json contained within in.// Returns a slice containing all subpaths with the root at the// passed in name and json value.func buildPathsBlindly( string, interface{}) []string { , := .(map[string]interface{})if ! || len() == 0 {return []string{} }// A google.protobuf.Struct/Value field carries arbitrary client JSON, so // its nesting depth is attacker controlled. Keep each queue entry pointing // at its parent and its own segment rather than carrying the full path // string, so a path is concatenated once at the leaf (O(depth)) instead of // rebuilding the growing prefix at every level (O(depth^2)). A deeply // nested object otherwise makes this allocate quadratically in the depth // while producing only a handful of paths.typestruct { *string }typestruct { *map[string]any }var []string := []{{: &{: }, : }}forlen() > 0 { := [0] = [1:]for , := range . { := &{: ., : }if , := .(map[string]any); && len() > 0 { = append(, {: , : })continue }// No populated object remains, so there are no more levels to // descend. Walk back to the root to materialize the path once.var []string := 0for := ; != nil; = . { = append(, .) += len(.) + 1 }varstrings.Builder .Grow( - 1)for := len() - 1; >= 0; -- { .WriteString([])if > 0 { .WriteByte('.') } } = append(, .String()) } }return}// fieldMaskPathItem stores an in-progress deconstruction of a path for a fieldmasktype fieldMaskPathItem struct {// the list of prior fields leading up to node connected by dots path string// a generic decoded json object the current item to inspect for further path extraction node interface{}// parent message msg protoreflect.Message}
The pages are generated with Goldsv0.8.7. (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu.
PR and bug reports are welcome and can be submitted to the issue list.
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds.