Define Your Domain Types as Protocol Buffers

Distributed Services with Go — by Travis Jeffery (19 / 84)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Install the Protocol Buffer Compiler | TOC | Compile Protocol Buffers 👉

In the previous chapter, we defined our Record type in Go as this struct:

LetsGo/internal/server/log.go

​ ​type​ Record ​struct​ {
​ Value []​byte​ ​`json:"value"`​
​ Offset ​uint64​ ​`json:"offset"`​
​ }

To turn that into a protobuf message we need to convert the Go code into protobuf syntax.

The convention for Go projects is to put your protobuf in an api directory. So run mkdir -p api/v1 to create your directories, then create a file called log.proto in the v1 directory and put this code in it:

StructureDataWithProtobuf/api/v1/log.proto

​ syntax = ​"proto3"​;

​ ​package​ ​log​.v1;

​ ​option​ go_package = ​"github.com/travisjeffery/api/log_v1"​;
​ ​message​ Record {
​ ​bytes​ value = 1;
​ ​uint64​ offset = 2;
​ }

In this protobuf code, we specify that we’re using proto3 syntax — the latest version of protobuf syntax. Then we specify a package name for two reasons: because this protobuf package name is used as the package name in the generated Go code and because it prevents name clashes between protocol message types that have the same name.

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.