-
从https://github.com/protocolbuffers/protobuf/releases下载protoc(如:Windows则下载protoc-3.6.1-win32.zip)。protoc命令位于bin目录下。
1cd ~ && wget https://github.com/protocolbuffers/protobuf/releases/download/v3.15.8/protoc-3.15.8-linux-x86_64.zip -O protoc.zip && unzip protoc.zip -
go get github.com/golang/protobuf/go get google.golang.org/protobuf
下载golang的package,用于程序中引入或生成二进制文件protoc-gen-go; -
编译github.com/golang/protobuf/protoc-gen-go。因protoc需调用protoc-gen-go,故需将protoc-gen-go放在环境变量PATH指定的目录中,或protoc所在的目录。
12345#如果总是下载失败,直接通过git下载到go的src/github.com/golang目录下echo $GOPATH && cd $GOPATHgit clone https://github.com/golang/protobuf.git && cd protobuf/protoc-gen-go && go build#生成protoc-gen-go拷贝到默认执行目录mv protoc-gen-go /usr/bin -
定义proto文件。如:
12345678910syntax = "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。
1protoc --proto_path=IMPORT_PATH --go_out=DST_DIR *.proto- --proto_path:同-I,指定proto文件的目录,缺省则为当前进程目录。
- --go_out:指定go文件生成目录。
-
调用(示例中假设生成的go代码位于path/to/example)。
123456789101112131415161718192021222324252627package mainimport ("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.}本文转自https://www.cnblogs.com/garvenc/p/use_protobuf_in_go.html
微信赞赏
支付宝赞赏