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:
.proto
is your document
Installation
- Install protocol buffer generator
- First, install
protoc
, which is the tool for transforming.proto
to program. - https://github.com/protocolbuffers/protobuf/releases install the protocol compiler
- After unzip, put the
bin/protoc
file 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/bin
to execute in terminal.
- Transform proto document
- Create a
example.proto
file
1 | // Format is Proto v3 |
protoc --go_out=. *.proto
transform to golang- And we will get a file
example.pb.go
which is belongs toprotobuf
plugin. - Then we can use this structure in golang.
- Decode and Encode
- Create a folder
/protobuf
, and putexample.pb.go
in it. - Create
main.go
1 | package main |
go run main.go
- Output
12345 Yu Wang Hello