Among the many ways to transmit representations, Google’s
Protobuf (short for “protocol buffer”) has gained traction.
With Protobuf, your representations (referred to as “messages” in the Protobuf
documentation) are defined in .proto files. Using the Protobuf compiler, the
definitions in the .proto files are then generated in your language(s) of
choice.
For a quick tutorial on using Protobuf with Go, check out
this tutorial.
So can we use Protobuf with negotiator? You bet! Let’s walk through it.
Create your .proto file
First things first - let’s create our .proto file containing the
definitions of the Protobuf messages. Suppose we have
an account resource for our API with this definition:
Next, we need to invoke the compiler to generate the corresponding Go types
that represent our messages. Based on our project structure, we invoked the
compiler like this:
The $PROJ_DIR is the directory for our project. The --proto_path option
specifies a directory in which to search for imports. The --go_opt=paths=source_relative
option allows us to place our generated source code in the same directory as
our .proto file. --go_out specifies the base directory in which to place
the generated source code. Finally, the final piece of the command is an
argument specifying the path the .proto file.
For more details, head over to the official documentation on how to use
the protoc compiler for Go.
Create your representations
Now that we have generated our Protobuf messages, we need to define our representations.
We do this by creating a Go type that implements
representation.Representation, and embeds our Protobuf
generated type as well as representation.Base:
Negotiate!
That’s it! With our HTTP handler below, we now have everything we need to
negotiate using Protobuf:
Finished code
Much of the code in this post was lifted from tutor, our sample RESTful API
demonstrating example use of the freerware product suite.