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相關