WIN7 + Go1.9.2+protobuf3.5.1
1.首先定义一个用于测试的proto文件test.proto,内容如下:
syntax = "proto3"; package example; message Test { string strTest = 1; double dTest = 2; repeated int64 i64RepsTest = 3; }
2.需要下载两个exe来生成对应的go文件
①https://github.com/google/protobuf/releases下载protoc-3.5.1-win32.zip文件,解压得到protoc.exe
②使用go get github.com/golang/protobuf/protoc-gen-go
下载生成go格式代码的插件(默认会下载到GOPATH/bin中,而GOPATH/bin默认是c:/Users/Administrator/go/bin),得到protoc-gen-go.exe
③将protoc.exe、protoc-gen-go.exe和test.proto拷贝到同一个文件夹中
④protoc.exe --go_out=. test.proto,生成对应的go代码文件test.pb.go
3.下面使用代码
①使用go get github.com/golang/protobuf/proto
安装protobuf库
②将生成的test.pb.go拷贝到项目中(这里必须注意,因为使用了package example,所以必须在项目中新建example文件夹再拷贝进去)
③在项目中使用protobuf库,以及引入Test
import ( "github.com/golang/protobuf/proto"
"../example" //这里根据项目结构决定example的位置
)
④测试代码(在这里测试了中文字符串,double数据以及int64的数据)
marshalTest := &example.Test{ *proto.String("test_string中文test"), *proto.Float64(2.34), []int64{123456789123, 4, 5}} data, err := proto.Marshal(marshalTest) if err != nil { fmt.Println("proto.Marshal err : ", err) } unmarshalTest := &example.Test{} err = proto.Unmarshal(data, unmarshalTest) if err != nil { fmt.Println("proto.Unmarshal err : ", err) } fmt.Println("strTest = ", unmarshalTest.GetStrTest()) fmt.Println("doubleTest = ", unmarshalTest.GetDTest()) for _, v := range unmarshalTest.GetI64RepsTest() { fmt.Println("int64 reps = ", v) }
输出的结果
以上。
参考博文:《golang使用protobuf》
PS:protobuf相关