From the course: Beginner's Guide to Go Protocol Buffer

How to define a protobuf messages - Go Tutorial

From the course: Beginner's Guide to Go Protocol Buffer

How to define a protobuf messages

- [Instructor] Now that we know all about protocol buffers let's start defining some. We'll be using the proto3 version for our definitions. Protobuf are .proto files and you can specify fields to be optional, repeated, or singular, but not required. Required has been removed since making a field required means you can never remove that field by the rules of Protobuf, so it's best not to make any field required and account for that in your code. First, we need to specify that we're using proto3. If not, the compiler will assume proto2. Then we define our request. Since it's a request format we're defining, we use the keyword word message. Next, the name of the request, in this case, SearchRequest. Then we just find some fields. We have a query, which we define as a string, and two int32 fields, page_number and result_per_page. Each field can be a scaler type like double, float, boolean, or bites, or it can be a type defined in the Protobuf. You also need to assign each field in the definition a unique number. These are used to identify the field in the message binary format, and shouldn't be changed once the field or message goes into use. The numbers have to be unique within the message definition and while you can remove a field, and thus it's number after it's gone into use, you cannot reuse that number within the definition. So in the cases like that, it's best to leave the field, but rename it with something like archived or deprecated so you know it's no longer in use. Message fields have rules. The field rules are singular, the default, when no other rule is specified. Optional, repeated, a similar concept to an array, and map. Yep, the key value type. You can also add comments in your .protofile profile using the C++ style of multi-line /*, and then closing with a */ or the inline double slash. You can have multiple message types defined in your file but for best practices, all messages within this file should be related. Like in the example, you can add the response message where you can see we can define a message type and use it in another message. You can import a message type from another Protobuf file. For example, if you want to define a header that has some universal fields that would help you trace through your services end-to-end, we'd want to import it into all of your Protobufs without having to repeat the code in every file. We can also nest types, so the SearchResponse message could also be defined like this. If you then want to access SearchResponses result, you'll refer to it as SearchResponse.result. You can use enums, or an empty message, for requests without a query or any parameters. In the next video, we will learn how to define services.

Contents