Protocol Buffer
Protocol Buffer is like json、xml, but smaller, faster, simplifier.
Only have to define data structure once, and it will generate the file which is match to your programming language automatically, let you use directly.
Structure is Document
Define data structure.
File should be .proto as suffix.
1  | // Format is Proto v3  | 
What is the number after each field?
In fact, these are protocol buffer’s id when using decode and encode.
These will make you remove one of the field without messing up entire data structure encoding or decoding.
Pros and Cons with Json
- More lightweight
 - Confusion: being encoded
 - Performance high
 - Much more convenient: structure is your data model, don’t have to create object to mapping these data
 - Clear, no need document: 
.protois your document 
Installation
- Install protocol buffer generator
 
- First, install 
protoc, which is the tool for transforming.prototo program. - https://github.com/protocolbuffers/protobuf/releases install the protocol compiler
 - After unzip, put the 
bin/protocfile to$PATH, this make us to use in terminal. 
- Install Golang plugin
 
go get -u github.com/golang/protobuf/{proto,protoc-gen-go}- Do 
touch .bash_profile, andexport PATH=$PATH:/Users/pingjing/go/binto execute in terminal. 
- Transform proto document
 
- Create a 
example.protofile 
1  | // Format is Proto v3  | 
protoc --go_out=. *.prototransform to golang- And we will get a file 
example.pb.gowhich is belongs toprotobufplugin. - Then we can use this structure in golang.
 
- Decode and Encode
 
- Create a folder 
/protobuf, and putexample.pb.goin it. - Create 
main.go 
1  | package main  | 
go run main.go- Output 
12345 Yu Wang Hello