- read

How to use gRPC and Protobuf to Stream Data in Golang

Jerry An 6

gRPC

gRPC is a high-performance, open-source framework for building remote procedure call (RPC) APIs. It uses Protocol Buffers (Protobuf) as its default data serialization format and supports bidirectional streaming, making it an ideal choice for building real-time applications.

In this tutorial, we will explore how to use gRPC and Protobuf to stream data in Golang. We will build a simple chat application that allows clients to join a chat room and send messages to each other in real-time using bidirectional streaming.

Prerequisite

You need to install the gRPC and Protobuf packages for Golang. You can do this by running the following command:

go get -u google.golang.org/grpc
go get -u github.com/golang/protobuf/protoc-gen-go

Step 1: Define Protobuf Message

Next, you need to define your gRPC service and messages in a .proto file. Here’s an example:

syntax = "proto3";
option go_package = "./;pb";

service ChatService {
rpc JoinChat (stream JoinRequest) returns (stream ChatMessage);
}

message JoinRequest {
string username = 1;
}

message ChatMessage {
string username = 1;
string message = 2;
}

This defines a ChatService with a JoinChat method that takes a stream of JoinRequest messages and returns a stream of ChatMessage messages.

Step 2: Generate Go code

Once you have defined your message types, you need to generate Go code from the .proto file.

Here’s an example command:

protoc --go_out=. \
--go_opt=paths=source_relative \
--go-grpc_out=. \
--go-grpc_opt=paths=source_relative \
path/to/your.proto

This will generate two files: message.pb.go and message_grpc.pb.go.

Step 3: Create a gRPC Serve

Now you can implement your gRPC server

package main

import (
"fmt"
"log"
"net"

"google.golang.org/grpc"

pb "github.com/grpc-streaming/pb"
)

type server struct {
pb.UnimplementedChatServiceServer
}

func (s *server) JoinChat(stream pb.ChatService_JoinChatServer) error…