Hey fellow coders, this is the second post of my Go series. You can check my last blog if you want to know how to set up your Go workspace. In this article, we are going to see what Protocol Buffers are, data format and how to implement it in a Go-based application.
What is Protocol Buffer?
Protocol Buffer is a data format, like JSON and XML which stores the structured data that can be serialized and deserialized. It is a data format developed by Google. The main advantage of Protobuf is that it is much smaller than the other formats.
Protobuf is 3 to 10 times smaller and 20 to 100 times faster than XML.
Now, let’s take a football game and represent the data in XML, JSON, and Protobuf.
XML:
JSON:
Protobuf:
The above shown protobuf format is the encoded byte of the string, starting from position 2 in the array. The string “Real Madrid” is spelled out: R:82, e:101 and so on.
To know about this encoding, please check out Google’s own documentation here: Proton Buffer Encoding .
At this scale, the size is mostly similar. But when we scale it to larger data, the size starts to show a huge difference.
So, now let’s bring Protobuf to our Go code.
Installing Packages
This will install the necessary packages and we are now ready.
Now, let’s go and define the protobuf for the game object.
Game.proto
We start by specifying the version syntax of proto. Here we set syntax to ‘proto3’. Next, we define the package in which this object is to be used. After that, we will define the format of our Game object. This consists of our message format of type Game which features the following fields, home, away, venue and date.
As we defined the proto file, we are going to compile it with the protoc.
This will generate a game.pb.go file, which has the auto-generated code. For a detailed understanding of this code, check out Google’s documentation: Go generated code .
main.go
In the above code, we use the Game struct defined in the game.pb.go to add details to the elClasico object. We use the Marshal function of the proto library to convert the object to the Protobuf format. Then the encoded bytes can be decoded with the Unmarshal function. Now we can use the function GetHome, GetAway generated in the game.pb.go file to get the values from the decoded object.
Don’t forget to include the game.pb.go. Now we have a small example up and running. But actually in the real world, the data is not going to be this simple. Now let’s see some nested fields.
We will use the same Game object. In this, we are taking the fields home and away and making it an object Team.
game.proto:
So again, we create the auto-generated code.
And we update the main.go file correspondingly.
main.go
Now if we run the program.
Interesting, isn’t it?
Alright guys, we now know how to use protocol buffer data format with Go. That’s it for now. Will meet you guys again with another interesting topic.