- 从https://github.com/protocolbuffers/protobuf/releases下载protoc(如:Windows则下载protoc-3.6.1-win32.zip)。protoc命令位于bin目录下。
- go get github.com/golang/protobuf。
- 编译github.com/golang/protobuf/protoc-gen-go。因protoc需调用protoc-gen-go,故需将protoc-gen-go放在环境变量PATH指定的目录中,或protoc所在的目录。
-
定义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- --proto_path:同-I,指定proto文件的目录,缺省则为当前进程目录。
- --go_out:指定go文件生成目录。
-
调用(示例中假设生成的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. }
本文详细介绍了如何使用Protocol Buffers(Protobuf)与Go语言进行整合,包括下载和配置protoc编译器,定义.proto文件,以及如何生成并使用Go代码。通过示例展示了数据序列化和反序列化的全过程。
1030

被折叠的 条评论
为什么被折叠?



