DEV Community

Cover image for Enter to gRPC in Go first server
Vic ShΓ³stak
Vic ShΓ³stak

Posted on • Updated on

Enter to gRPC in Go first server

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
Enter fullscreen mode Exit fullscreen mode
  • Second, install the protoc plugin (for Protocol Buffers v3):
$ go get -u github.com/golang/protobuf/protoc-gen-go
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

πŸ•“ 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
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

Generate Go code from .proto file

$ protoc -I api/proto --go_out=plugins=grpc:pkg/api api/proto/adder.proto
Enter fullscreen mode Exit fullscreen mode

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)
    }
}
Enter fullscreen mode Exit fullscreen mode
  • 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
}

Enter fullscreen mode Exit fullscreen mode

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/...
Enter fullscreen mode Exit fullscreen mode
  • Go to another console session and connect to server with Evans:
$ evans api/proto/adder.proto -p 8080
Enter fullscreen mode Exit fullscreen mode
  • 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
}
Enter fullscreen mode Exit fullscreen mode

✨ 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 articles (like this) on this blog, then post a comment below and subscribe to me. Thanks! 😻

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 projects that need your help (and stars) πŸ‘‡

  • πŸ”₯ gowebly: A next-generation CLI tool for easily build amazing web applications with Go on the backend, using htmx & hyperscript and the most popular atomic/utility-first 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.
  • πŸƒ yatr: Yet Another Task Runner allows you to organize and automate your routine operations that you normally do in Makefile (or else) for each project.
  • πŸ“š gosl: The Go Snippet Library provides snippets collection for working with routine operations in your Go programs with a super user-friendly API and the most efficient performance.
  • πŸ„β€β™‚οΈ csv2api: The parser reads the CSV file with the raw data, filters the records, identifies fields to be changed, and sends a request to update the data to the specified endpoint of your REST API.
  • 🚴 json2csv: The parser can read given folder with JSON files, filtering and qualifying input data with intent & stop words dictionaries and save results to CSV files by given chunk size.

Top comments (0)