本文更新於2019-01-03。
-
從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. }