Google uses protocol buffer encoding to build a web protocol called gRPC. It is a type of remote procedure call that uses HTTP/2 to establish connections and protocol buffers to marshal and unmarshal data.
The first step is generating code related to the server in the target language. This will produce a server interface and a client working implementation. Next, a server implementation needs to be created manually, and finally, the target language will enable the implementation to be used in a gRPC server and then use the client to connect and interact with it.
There are different examples in the go-grpc package, including a client/server pair. The client uses the generated code, which only needs a working gRPC connection to the server, and then it can use the methods specified in the service:
conn, err := grpc.Dial(address, grpc.WithInsecure())
if err != nil {
log.Fatalf("did not connect: %v", err)
}
defer conn.Close()
c := pb.NewGreeterClient(conn)
// Contact the server and print out its response
r, err := c.SayHello(ctx, &pb.HelloRequest{Name: name})
The full code is available at grpc/grpc-go/blob/master/examples/helloworld/greeter_client/main.go.
The server is an implementation of the client interface:
// server is used to implement helloworld.GreeterServer.
type server struct{}
// SayHello implements helloworld.GreeterServer
func (s *server) SayHello(ctx context.Context, in *pb.HelloRequest) (*pb.HelloReply, error) {
log.Printf("Received: %v", in.Name)
return &pb.HelloReply{Message: "Hello " + in.Name}, nil
}
This interface implementation can be passed to the generated register function, RegisterGreeterServer, together with a valid gRPC server, and it can serve incoming connections using a TCP listener:
func main() {
lis, err := net.Listen("tcp", port)
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
s := grpc.NewServer()
pb.RegisterGreeterServer(s, &server{})
if err := s.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err)
}
}
The full code is available at grpc/grpc-go/blob/master/examples/helloworld/greeter_server/main.go.