Services
Finally, the last construct that is important to see and that we are going to work with during this book is the service one. In Protobuf, a service is a collection of RPC endpoints that contains two major parts. The first part is the input of the RPC, and the second is the output. So, if we wanted to define a service for our accounts, we could have something like the following:
message GetAccountRequest {…} message GetAccountResponse {…} service AccountService { rpc GetAccount(GetAccountRequest) returns (GetAccountResponse); //... }
Here, we define a message representing a request, and another one representing the response and we use these as input and output of our getAccount
RPC call. In the next chapter, we are going to cover more advanced usage of the services, but right now what is important to understand is that Protobuf defines the services but does not generate the code for them. Only gRPC will.
Protobuf’s services are here to describe a contract, and it is the job of an RPC framework to fulfill that contract on the client and server part. Notice that I wrote an RPC framework and not simply gRPC. Any RPC framework could read the information provided by Protobuf’s services and generate code out of it. The goal of Protobuf here is to be independent of any language and framework. What the application does with the serialized data is not important to Protobuf.
Finally, these services are the pillars of gRPC. As we are going to see later in this book, we will use them to make requests, and we are going to implement them on the server side to return responses. Using the defined services on the client side will let us feel like we are directly calling a function on the server. If we talk about AccountService
, for example, we can make a call to GetAccount
by having the following code:
res := client.GetAccount(req)
Here, client
is an instance of a gRPC client, req
is an instance of GetAccountRequest
, and res
is an instance of GetAccountResponse
. In this case, it feels a little bit like we are calling GetAccount
, which is implemented on the server side. However, this is the doing of gRPC. It will hide all the complex ceremony of serializing and deserializing objects and sending those to the client and server.