Introduction to gRPC: Building a Golang Server and a PHP Client

OmidReza Salari
3 min readJun 12, 2024

--

GRPC has emerged as a powerful tool for building distributed systems and microservices in recent years. It offers a high-performance, language-agnostic framework for defining and consuming APIs. In this article, we will explore the basics of gRPC, and walk through a practical example of implementing a gRPC server in Golang and a client in PHP.

What is gRPC?

gRPC (gRPC Remote Procedure Calls) is an open-source framework developed by Google. It leverages HTTP/2 for transport, Protocol Buffers (protobuf) as the interface definition language, and offers features such as authentication, load balancing, and more.

Key benefits of gRPC include:

  • Efficient serialization: Using Protocol Buffers, gRPC allows for efficient and compact data serialization.
  • Language interoperability: gRPC supports multiple programming languages, making it ideal for polyglot environments.
  • Bi-directional streaming: gRPC supports various types of RPC, including unary, server streaming, client streaming, and bi-directional streaming.

Setting Up a gRPC Server in Golang

Let’s start by setting up a gRPC server using Golang. We will create a simple service that allows clients to perform basic operations like saying hello.

Step 1: Install Prerequisites

Before we begin, make sure you have Go installed. You can download it from the official site. Additionally, you will need protoc, the Protocol Buffers compiler, and the gRPC plugin for Go.

# Install protoc
brew install protobuf

# Install protoc-gen-go and protoc-gen-go-grpc
go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest

Step 2: Define the Protocol Buffers File

Create a directory for your project and define a .proto file.

// hello.proto
syntax = "proto3";

package hello;

service HelloService {
rpc SayHello (HelloRequest) returns (HelloResponse);
}

message HelloRequest {
string name = 1;
}

message HelloResponse {
string message = 1;
}

Step 3: Generate Go Code from the .proto File

Use protoc to generate Go code from the .proto file.

protoc --go_out=. --go-grpc_out=. hello.proto

Step 4: Implement the gRPC Server

Now, let’s implement the gRPC server in Go.

// server/main.go
package main

import (
"context"
"log"
"net"

"google.golang.org/grpc"
pb "path/to/your/proto/package" // Import the generated protobuf code
)

type server struct {
pb.UnimplementedHelloServiceServer
}

func (s *server) SayHello(ctx context.Context, req *pb.HelloRequest) (*pb.HelloResponse, error) {
message := "Hello, " + req.GetName()
return &pb.HelloResponse{Message: message}, nil
}

func main() {
lis, err := net.Listen("tcp", ":50051")
if err != nil {
log.Fatalf("failed to listen: %v", err)
}

s := grpc.NewServer()
pb.RegisterHelloServiceServer(s, &server{})

log.Printf("server listening at %v", lis.Addr())
if err := s.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err)
}
}

Setting Up a gRPC Client in PHP

Next, we’ll set up a gRPC client in PHP to interact with our Go server.

Step 1: Install Prerequisites

Ensure you have PHP installed on your system. You will also need Composer, the PHP package manager, and the gRPC PHP extension.

# Install Composer
php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"
php composer-setup.php
php -r "unlink('composer-setup.php');"

# Install gRPC PHP extension
pecl install grpc

# Install protobuf PHP extension
pecl install protobuf

Step 2: Install gRPC PHP Library

Use Composer to install the gRPC PHP library.

composer require grpc/grpc google/protobuf

Step 3: Generate PHP Code from the .proto File

It would help if you generated PHP classes from the .proto file. This requires the protoc compiler with the grpc_php_plugin.

protoc --php_out=./ --grpc_out=./ --plugin=protoc-gen-grpc=grpc_php_plugin hello.proto

Step 4: Implement the PHP Client

Finally, create a PHP script to act as the gRPC client.

// client.php
require 'vendor/autoload.php';
require 'GPBMetadata/Hello.php';
require 'Hello/HelloServiceClient.php';
require 'Hello/Hello.pb.php';

use Hello\HelloServiceClient;
use Hello\HelloRequest;

$client = new HelloServiceClient('localhost:50051', [
'credentials' => \Grpc\ChannelCredentials::createInsecure(),
]);

$request = new HelloRequest();
$request->setName('World');

list($response, $status) = $client->SayHello($request)->wait();

if ($status->code !== \Grpc\STATUS_OK) {
echo "Error: " . $status->details . PHP_EOL;
} else {
echo "Greeting: " . $response->getMessage() . PHP_EOL;
}

Running the Example

  1. Start the gRPC server:
go run server/main.go

2. Run the PHP client:

php client.php

You should see the following output:

Greeting: Hello, World

Conclusion

In this article, we have introduced gRPC and demonstrated how to set up a simple gRPC server in Golang and a client in PHP. gRPC’s efficiency and language interoperability make it an excellent choice for building scalable, high-performance APIs in polyglot environments. With this foundation, you can extend your services to include more complex logic and explore additional gRPC features such as streaming and authentication.

--

--