Install Protocol Buffers
The latest release of Protocol Buffers can be found on the release page https://github.com/protocolbuffers/protobuf/releases/tag/v3.9.1
Install Libraries
Make sure Git is installed on your machine and in your system’s PATH. Install the package to your $GOPATH with the go tool from shell:
$ go get google.golang.org/grpc
Create Proto Service
Create new folder named src. In src folder, create new folder named addservice. In addservice folder, create new folder named proto. In proto folder, create new file named add.proto as below:
syntax = "proto3";
package addservice;
service AddService {
rpc Add (AddRequest) returns (AddResponse);
}
message AddRequest {
double a = 1;
double b = 2;
}
message AddResponse {
double result = 1;
}
Generate Protocol Buffers
Select addservice folder and open it in Terminal window of Visual Studio Code. Use command line as below to generate add.pb.go file:
protoc -I ./ proto/add.proto --go_out=plugins=grpc:.
Create Handlers
In addservice folder, create new folder named handlers. In this folder, create new file named handler.go as below:
package handlers
import (
addservice "addservice/proto"
"context"
)
type AddServiceServer struct {
}
func (*AddServiceServer) Add(ctx context.Context, in *addservice.AddRequest) (*addservice.AddResponse, error) {
return &addservice.AddResponse{Result: in.A + in.B}, nil
}
Create Server
In addservice folder, create new folder named server. In this folder, create new file named main.go as below:
package main
import (
"addservice/handlers"
addservice "addservice/proto"
"fmt"
"net"
"google.golang.org/grpc"
)
func main() {
lis, err := net.Listen("tcp", ":1111")
if err != nil {
fmt.Println(err)
}
defer lis.Close()
addServ := handlers.AddServiceServer{}
grpcServer := grpc.NewServer()
addservice.RegisterAddServiceServer(grpcServer, &addServ)
if err := grpcServer.Serve(lis); err != nil {
fmt.Println(err)
}
}
Start Server
Select main.go file in server folder and open it in Terminal window of Visual Studio Code. Use command line as below to start server:
go run main.go
Create Client
In src folder, create new folder named client. In this folder, create new file named main.go as below:
package main
import (
addservice "addservice/proto"
"context"
"fmt"
"google.golang.org/grpc"
)
func main() {
conn, err := grpc.Dial(
"localhost:1111",
grpc.WithInsecure(),
)
if err != nil {
fmt.Println(err)
}
defer conn.Close()
addServ := addservice.NewAddServiceClient(conn)
response, err := addServ.Add(context.Background(), &addservice.AddRequest{A: 2, B: 5})
if err != nil {
fmt.Println(err)
} else {
result := response.Result
fmt.Println("Result: ", result)
}
}
Start Client
Select main.go file in client folder and open it in Terminal window of Visual Studio Code. Use command line as below to start client:
go run main.go
Output
Result: 7