loading...
Cover image for Enter to gRPC in Go β†’ first server

Enter to gRPC in Go β†’ first server

koddr profile image Vic ShΓ³stak ・Updated on ・4 min read

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

  1. Get started
  2. Repository with full code example
  3. Project structure
  4. Create proto file
  5. Create gRPC server
  6. 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:

grpc schema

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! 😏

  1. With Protocol Buffers you can easily describe structures;
  2. Built-in code generator will do the basic work for you;
  3. 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 πŸ‘Œ

GitHub logo koddr / example-go-grpc-server

Example gRPC server on Go

Just git clone and read instructions from README.

project structure

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 type x and y:
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

asciicast

Photo by

[Title] Lorenzo Herrera https://unsplash.com/photos/p0j-mE6mGo4
[1] Kaleidico https://unsplash.com/photos/26MJGnCM0Wc

P.S.

If you want more β€” write a comment below & follow me. Thx! 😘

Discussion

pic
Editor guide