protobuf example
Using protobuf to show data -> marshal -> snd -> rcv -> unmarshal -> data
.
These are my 6 main example of using protobuf,
Table of contents,
Documentation and reference,
GitHub Webpage
STEP 1 - DEFINE .proto FILE
Define a protocol buffer file messages.proto
that
declares the messages that are going to be serialized.
A message is just an aggregate containing a set of typed fields.
Structure for this example is,
message Person {
string name = 1;
int32 age = 2;
string email = 3;
string phone = 4;
uint32 count = 5;
}
STEP 2 - COMPILE .proto FILE
Compile the protocol buffer file to get the wrappers and
place this file in the same directory as protobuf.go.
cd protoc
protoc --go_out=. messages.proto
cp messages.pb.go ..
Results in messages.pb.go
that
implements all messages as go structs and types.
STEP 3 - IMPLEMENT (RUN)
Run the code,
go run protobuf.go messages.pb.go
THE FLOW
The flow to send data over a pipe is,
- DATA
- MARSHALL
- SEND
- RECEIVE
- UNMARSHAL
- DATA
Usually, you have two separate processes but I kept everything
inside one process to keep it simple.
DATA
Now lets create the message to send. Create a pointer
to a type Person struct.
sndPerson := &Person{
Name: "Jeff",
Age: 20,
Email: "blah@blah.com",
Phone: "555-555-5555",
Count: 1,
}
MARSHAL
sndMsg, err := proto.Marshal(sndPerson)
SEND
Now lets pretend we're sending the message sndMsg over a pipe.
pipe := sndMsg
RECEIVE
rcvMsg := pipe
UNMARSHAL -> DATA
Now lets create an empty pointer to the
same struct from our protobuf file and unmarshal it.
rcvPerson := &Person{}
err = proto.Unmarshal(rcvMsg, rcvPerson)
HIGH-LEVEL ILLUSTRATION
This illustration may help show what we did,
![IMAGE - protobuf - IMAGE](https://github.com/JeffDeCola/my-go-examples/raw/a2a1f0255beb/docs/pics/messaging/protobuf.jpg)