Protocol Buffers and GRPC in Go
Setup Compiling Protocol Buffer with protoc
To transfer data between the systems, we will make use of the compiled files from the proto
proto files. We will make use of the structs (gotten from the compiled files) to create the binary data.
Steps we will follow:
- Install the
protoc
comman-line tool and theproto
library - Write
.proto
file - Compile the file for
Go
target language - Import the structs from the generated file and create data using those
- Serialize the data into binary format and send it to the other system
- On the remote machine, de-serialize the data and consume it
We will install he protoc command line from https://github.com/protocolbuffers/protobuf/releases
For MAC and Linux
On mac
$ brew install protobuf
On Ubuntu or Linux, we can copy protoc to the /usr/bin folder:
Make sure you grab the latest version
Unzip
Move only protoc* to /usr/bin/
sudo mv protoc3/bin/protoc /usr/bin/protoc
After installing and setting up the command line tool, make sure you are able to access it from your terminal:
Referance link Protocol Buffers and GRPC in Go - DEV Community
GO local setup
go local needed to run protoc by adding the following lines to .bashrc ref link: protoc-gen-go: program not found or is not executable · Issue #795 · golang/protobuf · GitHub
Setup
Now in our project directory, create a new folder protofiles
and then in it let us create a proto file representing/modeling information:
chat.proto
The second line package protofiles
is the package name for go to compile.
To compile our chat.proto proto-buf file, cd
to the protofiles directory and run:
-
go get -u github.com/golang/protobuf/protoc-gen-go
protoc-gen-go is a plugin for the Google protocol buffer compiler to generate Go code. -
protoc --go_out=plugins=grpc:chat ./protofiles/chat.proto
this will create a Go target file in the present working directory from where the command is run (the dot) and make use of all the proto files to do so
This will generate a chat.pb.go
file. If you open this file you will see that it contains the auto generated code for us.
This will have multiple getter
and setter
methods for the structs to get and set the values.