Search⌘ K
AI Features

Solution 4: Working with gRPC

Explore the implementation of gRPC services in Go by defining protocol buffers and creating server and client code. Understand how to build RPC methods for addition and subtraction and how to handle requests and responses using Go's gRPC framework.

We'll cover the following...

Solution

To execute the client side, open a new terminal window and run the following commands:

export GOROOT=/usr/local/go; export GOPATH=$HOME/go; export PATH=$GOPATH/bin:$GOROOT/bin:$PATH; cd usercode;
go run gClient.go

Here is the gRPC service that implements integer addition and subtraction:

syntax = "proto3";

option go_package = "./;protoapi";

service Math {
    rpc Add (MathRequest) returns (MathResult);
    rpc Subtract (MathRequest) returns (MathResult);
}

message MathRequest {
    int64 Operand1 = 1;
    int64 Operand2 = 2;
}

message MathResult {
    int64 Result = 1;
}
gServer.go and gClient,go

Code explanation

Let's look at the code explanation of each file. Following is the code explanation of the protoapi/protoapi.proto file:

  • Line 5: This defines the gRPC service named Math.

  • Line 6: This defines an RPC method named Add that takes a MathRequest message as input and returns a MathResult message as output. This method will perform addition.

  • Line 7: This defines another RPC ...