Home > Net >  golang:convert proto.any to proto.struct
golang:convert proto.any to proto.struct

Time:05-12

I have a field type proto.Any passed from upstream service, and I need to convert it to proto.Struct. I see there is a UnmarshalAny function but it only takes proto.Message. Anybody can help

CodePudding user response:

End up going with types.Any -> proto message -> jsonpb -> types.Struct

CodePudding user response:

As Jochen mentioned in the comments, you can use anypb and structpb to manage the respective Well Known Types. So you will first import the followings:

"google.golang.org/protobuf/types/known/anypb"
"google.golang.org/protobuf/types/known/structpb"

and then it is basically just marshalling and unmarshalling process:

s := &structpb.Struct{
    Fields: map[string]*structpb.Value{
        "is_working": structpb.NewBoolValue(true),
    },
}

any, err := anypb.New(s) // transform `s` to Any
if err != nil {
    log.Fatalf("Error while creating Any from Struct")
}

m := new(structpb.Struct)
if err = any.UnmarshalTo(m); err != nil { // transform `any` back to Struct
    log.Fatalf("Error while creating Struct from Any")
}

log.Println(m)

Note that I don't know you proto definition so here instead of doing the any.New marshalling part, you will replace that with the any you receive from your upstream service.

let me know how I can better help.

  • Related