Using Protobuf with Go
suggest changeThe sample below is the older proto2 API and the github.com/golang/protobuf module. Current code uses proto3 and google.golang.org/protobuf. Put the message in test.proto:
syntax = "proto2";
package example;
enum FOO { X = 17; };
message Test {
required string label = 1;
optional int32 type = 2 [default=77];
repeated int64 reps = 3;
optional group OptionalGroup = 4 {
required string RequiredField = 5;
}
}
To compile the protocol buffer definition, run protoc with the –go_out parameter set to the directory you want to output the Go code to.
$ protoc --go_out=. *.proto
To create and play with a Test object from the example package,
package main
import (
"log"
"github.com/golang/protobuf/proto"
"path/to/example"
)
func main() {
test := &example.Test {
Label: proto.String("hello"),
Type: proto.Int32(17),
Reps: []int64{1, 2, 3},
Optionalgroup: &example.Test_OptionalGroup {
RequiredField: proto.String("good bye"),
},
}
data, err := proto.Marshal(test)
if err != nil {
log.Fatal("marshaling error: ", err)
}
newTest := &example.Test{}
err = proto.Unmarshal(data, newTest)
if err != nil {
log.Fatal("unmarshaling error: ", err)
}
// Now test and newTest contain the same data.
if test.GetLabel() != newTest.GetLabel() {
log.Fatalf("data mismatch %q != %q", test.GetLabel(), newTest.GetLabel())
}
// etc.
}
plugins=grpc is no longer accepted. Generate gRPC stubs with the separate plugin:
$ protoc --go_out=. --go-grpc_out=. *.proto
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents