This is a creation in Article, where the information may have evolved or changed.
Protobuf is a language-independent, platform-independent data serialization tool developed by Google that can be used in many scenarios, such as RPC or TCP communication. In layman's terms, if the client and server are using different languages, a data structure is defined on the server, and the data structure can be obtained by converting the protobuf into a byte stream and then transmitting to the client decoder. This is the magical place of Protobuf. And, its communication efficiency is very high, "a message data, the size after serialization with PROTOBUF is one of JSON 10, one of the XML format of 20, is a binary serialization of one of 10".
Installation
wget https://github.com/google/protobuf/releases/download/v2.6.1/protobuf-2.6.1.tar.gz tar zxvf protobuf-2.6.1.tar.gz cd protobuf-2.6.1./configure make make install 执行 protoc -h 查看安装是否成功
go get github.com/golang/protobuf/protoc-gen-go
go get github.com/golang/protobuf/proto
Use in Go
The use of Protobuf is to write the data structure into a. proto file and compile it using the PROTOC compiler (which uses the plug-in indirectly) to get a new go package that contains the data structures and auxiliary methods you can use in go.
Writing Test.proto files
package example; enum FOO { X = 17; }; message Test { required string label = 1; optional int32 type = 2 [default=77]; repeated int64 reps = 3; optional group OptionalGroup = 4 { required string RequiredField = 5; } } 编译: 执行 protoc --go_out=. *.proto 生成 test.pb.go 文件 将test.pb.go文件放入example文件夹(对应上面package)中,作为example包
Try
Package Main import ("Log" "Github.com/golang/protobuf/proto" "Example") Fu NC Main () {test: = &example. Test {Label:proto. String ("Hello"), Type:proto. Int32 (+), Reps: []int64{1, 2, 3}, Optionalgroup: &example. Test_optionalgroup {Requiredfield:proto. String ("Good Bye"),},} 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 ())}//test. Getoptionalgroup (). Getrequiredfield ()//etc}
Some correspondence relationship
The message test pair is a struct struct with a corresponding get method for its property fields, and test can be used in go. Getlabel (), test. GetType () Gets the properties of the test object
Optionalgroup corresponds to an inline struct in a struct
Repeated property in proto file for slice structure
Test. Reset () to set all its properties to a value of 0
Easy encoding and decoding with Marshal and Unmarshal
These are just some of the features that you want to study carefully to see Wiki:https://github.com/golang/pro on GitHub ...