Quick Summary:

This tutorial enables you to understand and learn about Golang gRPC service. Using Go programming language, get the step-by-step points to create a gRPC (Google Remote Procedure Call).

Table of Contents

Introduction to gRPC

Let us begin by understanding what is gRPC.

gRPC is a high-performance remote procedure call RPC framework, given by Google. It is open-source and enables client-server communication over the transport protocol HTTP2.

In Golang, gRPC is implemented through the use of protocol buffers and code generation, which provides a fast and efficient way to build client-server applications.

Overall, there are two ways of creating web services, Rest API and RPC. Let’s get to know the difference between the two.

gRPC vs REST

gRPC and RESTful APIs are different ways of building web services.

gRPC is designed to be faster and more efficient than RESTful APIs, using a binary data format called Protocol Buffers instead of text-based formats like JSON. Whereas RESTful APIs are more flexible and allow for easier versioning, making them a good choice for web applications requiring frequent changes.

gRPC is also more strict in its rules and requires developers to define an interface in advance, which helps with error checking and data validation.

Overall, gRPC is ideal for internal communication between two microservices and a good choice for high-performance applications that must be fast and efficient. However, RESTful APIs are a better choice for applications that require more flexibility and frequent updates.

As we move ahead with gRPC to create a web service using gRPC, let us grab attention for the most essential benefit, i.e serialization of data using Protocol Buffers.

Building a cloud-native gRPC service in Golang can be a daunting task
Don’t waste your time and resources struggling to do it yourself. Hire Golang developer from us to get a reliable and scalable solution that meets your needs.

Protocol Buffers in Golang gRPC

Commonly known as protobuf, protocol buffer is a data serialization (irrespective of the programming language) format used in gRPC Golang. It is a compact and efficient way to serialize structured data into a binary format, which can then be sent over the network or stored on disk.

In gRPC with Golang, protocol buffers are defined using a special syntax in a .proto file, which is then compiled into Go code that can be used to deserialize or serialize data. The Go code generated from the .proto file provides type-safe access to the data and makes it easy to work with.

Protocol Buffers are a key feature of gRPC because they provide efficient serialization and deserialization of data, which is essential for high-performance network communication. They also enable developers to define a strict interface for their services using IDL, which helps ensure that different components of the system can communicate with each other properly.

Protocol Buffers in Golang gRPC

We will see an example of building a Golang gRPC service.

Prerequisites for Golang gRPC Example

As you wish to create a remote procedure call web service using gRPC Golang, here is the list of things you must be familiar with and have installed in your system for this gRPC Golang example.

  • Protoc compiler

For Ubuntu:

Copy Text
sudo apt-get install protobuf-compiler

For macOS:

Copy Text
brew install protoc

Guided Tutorial to Create Golang gRPC Server

To create a web service using the gRPC server in Golang, here are the steps we will follow:

  • Creating Proto file
  • Converting Proto file to Go file
  • Inheriting the gRPC interface
  • Creating the Client call service

Step 1: Creating Proto File

Create one proto file name with greeeing.proto

Copy Text
syntax = "proto3";

option go_package = "/pb";

service GreetingService {
    rpc Greeting(GreetingServiceRequest) returns (GreetingServiceReply) {}
}

message GreetingServiceRequest {
    string name = 1;
}

message GreetingServiceReply {
    string message = 2;
}

Step 2: Converting Proto File to Go File

Now We need to convert this proto file into a Go file

Copy Text
protoc <proto-file-path> --go_out=<output-file-path> --go-grpc_out=<output-file-path>
protoc *.proto --go_out=./ --go-grpc_out=./
  • After executing the above command, we can see two files are generated in pb directory
  • In greeting_grpc.pb.go, one interface is auto-generated
Copy Text
type GreetingServiceServer interface {
	Greeting(context.Context, *GreetingServiceRequest) (*GreetingServiceReply, error)
}

Step 3: Inheriting The gRPC Interface

Now we need to inherit and implement the above interface.

Copy Text
package main

import (
	"context"
	"fmt"
	"grpc-golang/pb"
	"log"
	"net"

	"google.golang.org/grpc"
)

type server struct {
	pb.GreetingServiceServer
}

func (s *server) Greeting(ctx context.Context, req *pb.GreetingServiceRequest) (*pb.GreetingServiceReply, error) {
	return &pb.GreetingServiceReply{
		Message: fmt.Sprintf("Hello, %s", req.Name),
	}, nil
}

func main() {
	listener, err := net.Listen("tcp", ":8080")
	if err != nil {
		panic(err)
	}

	s := grpc.NewServer()
	pb.RegisterGreetingServiceServer(s, &server{})
	if err := s.Serve(listener); err != nil {
		log.Fatalf("failed to serve: %v", err)
	}
}
  • We implemented the interface method with server struct
Copy Text
func (s *server) Greeting(ctx context.Context, req *pb.GreetingServiceRequest) (*pb.GreetingServiceReply, error) {
	return &pb.GreetingServiceReply{
		Message: fmt.Sprintf("Hello, %s", req.Name),
	}, nil
}
  • and register server struct with greeting server
Copy Text
pb.RegisterGreetingServiceServer(s, &server{})
  • now we can start our server file with go run server.go

Step 4: Creating the Client Call Service

After the server starts, we need to write the client to call the greeting method.

Copy Text
package main

import (
	"context"
	"fmt"
	"grpc-golang/pb"
	"log"
	"google.golang.org/grpc"
)

func main() {
	opts := grpc.WithInsecure()
	cc, err := grpc.Dial("localhost:8080", opts)
	if err != nil {
		log.Fatal(err)
	}
	defer cc.Close()

	client := pb.NewGreetingServiceClient(cc)
	request := &pb.GreetingServiceRequest{Name: "Gophers"}

	resp, err := client.Greeting(context.Background(), request)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Printf("Receive response => %s ", resp.Message)
}

Here we use the same auto-generated file for creating request and call greeting method

Copy Text
client := pb.NewGreetingServiceClient(cc)
request := &pb.GreetingServiceRequest{Name: "Gophers"}

resp, err := client.Greeting(context.Background(), request)
if err != nil {
  log.Fatal(err)
}

With this, we come to the end of this gRPC Golang tutorial. You may find the entire tutorial on our GitHub repo.

Conclusion

By following this tutorial, you now have a basic understanding of how to use gRPC in Go to build high-performance, scalable, and efficient microservices. With this knowledge, you can start building your own Golang gRPC services and take advantage of the benefits of this modern RPC framework.

Have a look at our other Golang Tutorials for more information on similar and other queries. Also, you can collaborate with a top-rated Golang development company like Bacancy for efficient, future-proof development.

Frequently Asked Questions (FAQs)

gRPC is a high-performance, language-agnostic RPC framework that uses efficient serialization and contract-based development. It offers strong typing and bi-directional communication, making it an excellent choice for building scalable and efficient microservices.

Golang gRPC can be used in various use cases, including microservices, real-time applications, IoT applications, machine learning implementations, etc.

Yes, gRPC is designed to be language-agnostic, meaning it can be used to build applications in any programming language.

Ready to Explore The Limitless Possibilities of Golang gRPC?

Our team of experts is here to help. We’ll work with you every step of the way to ensure that your solution is reliable, scalable, and high-performing. Contact us now!

BOOK A 30 MIN CALL

Build Your Agile Team

Hire Skilled Developer From Us

[email protected]

Your Success Is Guaranteed !

We accelerate the release of digital product and guaranteed their success

We Use Slack, Jira & GitHub for Accurate Deployment and Effective Communication.

How Can We Help You?