gRPC is designed to work across different languages and platforms. In this section, we will write a client in GO and invoke the CalculatorServer which we have implemented in Java.
package main
import (
"context"
"fmt"
"cse.cslab/goclient/calculator"
"google.golang.org/grpc"
"os"
)
func main() {
//Create a grpc connection to `CalculatorServer`
conn, err := grpc.Dial("127.0.0.1:8980", grpc.WithInsecure(), grpc.WithBlock())
if err != nil{
println("Can't create connection to server !!");
os.Exit(-1)
}
//Create a stub of Calculator service for invoking the method of Calculator service later on
client := calculator.NewCalculatorClient(conn)
// Calculate "1 + 1" by calling the CalculatorService
var a float32 = 1.0
var b float32 = 1.0
//Create the `CalculationRequest` object and set the value of `a` and `b`
requestObj := calculator.CalculationRequest{A:a, B:b}
//Invoking the `sum` function of `CalculatorService` through the stub
respondObj, err := client.Sum(context.Background(), &requestObj)
fmt.Printf("GoClient: The result of %f + %f = %f \n", a, b, respondObj.Result)
// Calculate "3 x 2" by calling the CalculatorService
a = 3.0
b = 2.0
requestObj = calculator.CalculationRequest{A:a, B:b}
respondObj, err = client.Product(context.Background(), &requestObj)
fmt.Printf("GoClient: The result of %f x %f = %f \n", a, b, respondObj.Result)
}
go get github.com/golang/protobuf/proto
go get golang.org/x/net/context
go get google.golang.org/grpc