protobuf data format is an efficient, platform-independent, language-independent, scalable, and can be used for continuous data storage system RPC system.
protobuf
protobuf Introduction
Protobuf
Is Protocol Buffer
short, it is independent of Google Inc. in 2008, a highly efficient open-source platform, language-independent, scalable data formats, as currently Protobuf interface description language specification can be used as the basis for the Go language RPC interface tool.
protobuf use
protobuf
A data protocol is a language-independent, so we need to write IDL file is then generated by means of a special tool to specify the language of the code to achieve serialization and de-serialization process data.
Development process substantially as follows: preparation of the specified language generated code 2. 1. IDL 3. serialization and deserialization
protobuf grammar
Compiler installation
ptotoc
protobuf
Agreement with c ++ compiler is written in, download the corresponding version of the operating system according to their own protoc
compilers: https://github.com/protocolbuffers/protobuf/releases , after decompression copied to the GOPATH/bin
directory.
protoc-gen-go
Go installation tool generates code language
go get -u github.com/golang/protobuf/protoc-gen-go
Code written in IDL
In protobuf_demo/address
the new one called directory person.proto
file contents are as follows:
// 指定使用protobuf版本
// 此处使用v3版本
syntax = "proto3";
// 包名,通过protoc生成go文件
package address;// 性别类型
// 枚举类型第一个字段必须为0
enum GenderType {
SECRET = 0;
FEMALE = 1;
MALE = 2;
}// 人
message Person {
int64 id = 1;
string name = 2;
GenderType gender = 3;
string number = 4;
}// 联系簿
message ContactBook {
repeated Person persons = 1;
}
```生成go语言代码
在
protobuf_demo/address
目录下执行以下命令。address $ protoc --go_out=. ./person.proto
此时在当前目录下会生成一个
person.pb.go
文件,我们的Go语言代码里就是使用这个文件。 在protobuf_demo/main.go
文件中:package main import ( "fmt" "io/ioutil" "github.com/golang/protobuf/proto" "github.com/Q1mi/studygo/code_demo/protobuf_demo/address" ) // protobuf demo func main() { var cb address.ContactBook p1 := address.Person{ Name: "小王子", Gender: address.GenderType_MALE, Number: "7878778", } fmt.Println(p1) cb.Persons = append(cb.Persons, &p1) // 序列化 data, err := proto.Marshal(&p1) if err != nil { fmt.Printf("marshal failed,err:%v\n", err) return } ioutil.WriteFile("./proto.dat", data, 0644) data2, err := ioutil.ReadFile("./proto.dat") if err != nil { fmt.Printf("read file failed, err:%v\n", err) return } var p2 address.Person proto.Unmarshal(data2, &p2) fmt.Println(p2) }