Serialization objects with protocol buffers in Golang

What is protocol buffers?

Protocol Buffers is a method of serializing structured data. It is useful in
developing programs to communicate with each other over a wire or for storing
data. The method involves an interface description language that describes the
structure of some data and a program that generates source code from that
description for generating or parsing a stream of bytes that represents the
structured data.

Google developed Protocol Buffers for use internally and has made protocol
compilers for C++, Java and Python available to the public under a free
software, open source license. Various other language implementations are also
available, including C#, JavaScript, Go, Perl, PHP, Ruby, Scala and Julia.

The design goals for Protocol Buffers emphasized simplicity and performance. In
particular, it was designed to be smaller and faster than XML.

Protocol Buffers is widely used at Google for storing and interchanging all
kinds of structured information. The method serves as a basis for a custom
remote procedure call (RPC) system that is used for nearly all inter-machine
communication at Google.

A software developer defines data structures (called messages) and services in
a proto definition file (.proto) and compiles it with protoc. This compilation
generates code that can be invoked by a sender or recipient of these data
structures.

The messages are serialized into a binary wire format which is
compact, forward- and backward-compatible, but not self-describing (that is,
there is no way to tell the names, meaning, or full datatypes of fields without
an external specification).

Though the primary purpose of Protocol Buffers is to facilitate network
communication.

Installation

Install the Golang packages to work with protocol buffers. I recommend using
the gogo protocol buffers fork that is
performance optimized. Like most of the go package, we should install it by
executing the following commands:

In order to use protocol buffers, you should define a protocol buffer file that
declare the messages that are going to be serialized. The protocol buffers
provide a syntax for doing that. You can specify whether a field should be optional
or required as well. Enumeration types can be defined as well. If you have a message
that is used only as property of another message, you can inline the define it
by using group declaration.

The protocol buffers supports the common scalar types, strings, enums and slices.
Slice fields can be defined as repeated fields.

Conclusion

The advantage of using protocol buffers is that you can develop heterogeneous
system in multiple languages and technologies which are communicating via known
protocol. It has better performance than standar serialization like JSON.