标签:fun href lease port syntax github require required lin
本文更新于2019-01-03。
定义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;
}
使用protoc生成go代码,生成的文件名为*.pb.go。
protoc --proto_path=IMPORT_PATH --go_out=DST_DIR *.proto
调用(示例中假设生成的go代码位于path/to/example)。
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},
}
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.
}
标签:fun href lease port syntax github require required lin
原文地址:https://www.cnblogs.com/garvenc/p/use_protobuf_in_go.html