Member-only story
Writing a Simple gRPC Application in Golang From Scratch
gRPC is a modern open-source, high-performance Remote Procedure Call (RPC) framework that can run in any environment. It is best suitable for internal communication between microservices.
Let’s build a simple gRPC application from scratch to understand gRPC better.
Building a Microservice in Golang
Let’s use an example of a book service to demonstrate how to use the gRPC framework. The complete code is on GitHub
This service will have five methods:
- CreateBook
- RetrieveBook
- UpdateBook
- DeleteBook
- ListBook
Define A Protobuf File
gRPC uses the Protobuf .proto
file format to define the messages, services, and some aspects of the code generation.
Messages are underlying interchange format.
In our example, we define a message type Book
that contains a field name, author, price, etc.
syntax = "proto3";package api.v1;import "google/protobuf/timestamp.proto";
option go_package = "github.com/jerryan999/book-service/api/v1";message Book {
int64 bid = 1;
string title = 2;
string author = 3;
string description = 4;
string language = 8;
google.protobuf.Timestamp finish_time = 9;
}...
There are a couple of things to note in this short example.
- We're using the latest version of the protobuf syntax
proto3
- Protobufs has its’ own timestamp type, so we need to use it properly.
If we want to use message types with an RPC (Remote Procedure Call) system, we must define an gRPC service interface in a .proto
file.
Service defines rpc methods for remote calling
service BookService { rpc CreateBook(CreateBookRequest) returns (CreateBookResponse) {}; rpc…