Deserialize objects in golang using protobuf
Problem
I want to deserialize an object in golang using protobuf.
For example, we want to deserialize the feedback report object in golang
using protobuf to check the feedbackUserCtlConsent value in it.
Solution
Key steps:
-
Add
go packagefor the proto. For example, the feedback report proto has proto files under~/chromiumos/src/platform2/feedback/components/feedback/protoWe add the following
go packageto all of the files in this directory.option go_package = "chromiumos/tast/local/bundles/cros/feedback/proto";The
go packagedirectory is the place to generate the pb.go files. -
Go to correct directory to run command line and generate the pb.go files. For example, I want to put the pb.go files in
src/platform/tast-tests/src/chromiumos/tast/local/bundles/cros/feedback/protoI should go to the directory where the proto files located
~/chromiumos/src/platform2/feedback/components/feedback/protoand run this command line.
protoc -I . --go_out=../../../../../platform/tast-tests/src ./*.proto -
Import
"github.com/golang/protobuf/proto"and go package directory to the test file. For example, I add
"github.com/golang/protobuf/proto"and
fpb "chromiumos/tast/local/bundles/cros/feedback/proto"to the
VerifyFeedbackUserCtlConsentValuetest. -
Use
Unmarshalto deserialize the object.report := &fpb.ExtensionSubmit{} if err = proto.Unmarshal(content, report); err != nil { s.Fatal("Failed to parse report: ", err) } -
Call the getter function in pb.go files to get the value in the object.
// Loop through the report array to get the feedbackUserCtlConsent value. feedbackUserCtlConsentValue := "" reportArray := report.GetWebData().GetProductSpecificData() for _, element := range reportArray { if element.GetKey() == "feedbackUserCtlConsent" { feedbackUserCtlConsentValue = element.GetValue() break } }
Example CL
- https://crrev.com/c/3943209
- https://crrev.com/c/3940029
References
- Protocol Buffer Basics: Go{.external}
- Go Generated Code{.external}