Introduction
Hey, friends! π I postponed this article series for a long time, because I was not sure how I felt about gRPC. But now, I've done one micro-service using this technology and...
I'm ready to talk about it! π
Table of contents
- Get started
- Repository with full code example
- Project structure
- Create proto file
- Create gRPC server
- The Call from gRPC client
Get started
gRPC is an open source high performance RPC framework, who can run in any environments and written on many programming languages.
βοΈ Good to know: Remote Procedure Call (RPC, for a short) is a powerful technique for constructing distributed, client-server based applications.
Main features
- Start quickly and scale
- Simple service definition
- Works across languages and platforms
- Bi-directional streaming and integrated auth
How it works?
Please, see diagram below for a better understanding of how gRPC works:
That is, if you have written a service on C++ or Go, but your colleagues write in Java or Ruby β it's not a problem at all. Give them your .proto
file and they will generate their own code for the client part! πΏ
β οΈ I'm not aiming at a total parse of all nuances of gRPC and its ecosystem. I leave that to you as homework assignment.
Protocol Buffers
Follow official Google Developer Guide for protobuf
:
Protocol buffers are a flexible, efficient, automated mechanism for serializing structured data [...] You define how you want your data to be structured once, then you can use special generated source code to easily write and read your structured data [...] You can even update your data structure without breaking deployed programs [...]
But what does it really mean? It's easier than it looks! π
- With Protocol Buffers you can easily describe structures;
- Built-in code generator will do the basic work for you;
- No problem to switch to another programming language;
How to install?
Go to Protocol Buffers download page and install latest version for your system (supported Windows, GNU/Linux and macOS).
β¨ Tip: macOS users can install Protocol Buffers from Homebrew.
$ brew install protobuf
Packages for use gRPC in Golang
- First, install the
go-grps
package:
$ go get -u google.golang.org/grpc
- Second, install the
protoc
plugin (for Protocol Buffers v3):
$ go get -u github.com/golang/protobuf/protoc-gen-go
That's all you need to get started! Now, you're ready to generate Go code from your
.proto
files.
gRPC client
The development of the gRPC client is beyond the scope of this article, so let's use turnkey solution β Evans β universal gRPC client.
- Install Evans:
$ go get -u github.com/ktr0731/evans
π No time to read more?
I created repository with full code example on my GitHub especially for you π
koddr / example-go-grpc-server
Example gRPC server on Go
Just git clone
and read instructions from README
.
Project structure
$ tree .
.
βββ Makefile
βββ go.mod
βββ go.sum
βββ api
β βββ proto
β βββ adder.proto <-- proto file
βββ cmd
β βββ server
β βββ main.go <-- main app
βββ pkg
βββ adder
β βββ grpcserver.go <-- methods for gRPC server
βββ api
βββ adder.pb.go <-- auto generated code from .proto file
Create proto file
// ./api/proto/adder.proto
syntax = "proto3"; // use proto file v3
package api; // name of package
// Define service Adder
service Adder {
rpc Add (AddRequest) returns (AddResponse) {}
}
// Define service methods
message AddRequest {
int32 x = 1; // Unique ID number for X
int32 y = 2; // Unique ID number for Y
}
message AddResponse {
int32 result = 1; // Unique ID number for result
}
Generate Go code from .proto
file
$ protoc -I api/proto --go_out=plugins=grpc:pkg/api api/proto/adder.proto
It generated adder.pb.go
file with complete Go code on folder ./pkg/api
π
Create gRPC server
- Main app:
// ./cmd/server/main.go
package main
import (
"log"
"net"
"github.com/koddr/example-go-grpc-server/pkg/adder"
"github.com/koddr/example-go-grpc-server/pkg/api"
"google.golang.org/grpc"
)
func main() {
// Create new gRPC server instance
s := grpc.NewServer()
srv := &adder.GRPCServer{}
// Register gRPC server
api.RegisterAdderServer(s, srv)
// Listen on port 8080
l, err := net.Listen("tcp", ":8080")
if err != nil {
log.Fatal(err)
}
// Start gRPC server
if err := s.Serve(l); err != nil {
log.Fatal(err)
}
}
- Methods for gRPC server:
// ./pkg/adder/grpcserver.go
package adder
import (
"context"
"github.com/koddr/example-go-grpc-server/pkg/api"
)
// GRPCServer struct
type GRPCServer struct{}
// Add method for calculate X + Y
func (s *GRPCServer) Add(ctx context.Context, req *api.AddRequest) (*api.AddResponse, error) {
return &api.AddResponse{
Result: req.GetX() + req.GetY(),
}, nil
}
The Call from gRPC client π²
We're ready to make our first gRPC call:
- Run gRPC server by command (from root of project folder):
$ go run ./cmd/server/...
- Go to another console session and connect to server with Evans:
$ evans api/proto/adder.proto -p 8080
- Into Evans, call to
Add()
method and typex
andy
:
api.Adder@127.0.0.1:8080> call Add
x (TYPE_INT32) => 10
y (TYPE_INT32) => 5
{
"result": 15
}
β¨ Tip: Evans support full auto-complete. Just use arrows and hit
Tab
for apply suggestion.
πΊ Evans live demo
Photo by
[Title] Lorenzo Herrera https://unsplash.com/photos/p0j-mE6mGo4
[1] Kaleidico https://unsplash.com/photos/26MJGnCM0Wc
P.S.
If you want more articles (like this) on this blog, then post a comment below and subscribe to me. Thanks! π»
βοΈ You can support me on Boosty, both on a permanent and on a one-time basis. All proceeds from this way will go to support my OSS projects and will energize me to create new products and articles for the community.
And of course, you can help me make developers' lives even better! Just connect to one of my projects as a contributor. It's easy!
My main projects that need your help (and stars) π
- π₯ gowebly: A next-generation CLI tool that makes it easy to create amazing web applications with Go on the backend, using htmx, hyperscript or Alpine.js and the most popular CSS frameworks on the frontend.
- β¨ create-go-app: Create a new production-ready project with Go backend, frontend and deploy automation by running one CLI command.
Top comments (0)