Get started with Golang and gRPC
Are you exploring which language and framework to choose for your new micro-service? If yes, Golang and gRPC could be the perfect choice. In this article, we will explore why Golang and gRPC is the ideal combination for your micro-service, and will provide a step-by-step guide on how to get started from scratch.
Why use Golang?
Efficiency and Performance: Golang prioritizes performance, delivering fast execution and low memory overhead through native machine code compilation.
Concurrent and Scalable: Golang’s Goroutines and channels enable concurrent task execution, enhancing microservices’ scalability and resource utilization.
Strong Standard Library: Golang comes with a robust standard library offers essential packages for networking, file handling, encryption, simplifying development with reduced external library dependencies.
Growing community: Golang, backed by Google and supported by a thriving open-source community, offers high performance, strong concurrency support, and a growing popularity, making it an excellent choice for modern applications and services.
Summing up, Golang’s low memory footprint, fast execution times, and concurrency features make it an excellent choice for building scalable microservices architectures.
Why use gRPC over REST ?
gRPC works on HTTP/2, which supports features like multiplexing and bidirectional communication which is not present in REST built on top of HTTP1.1.
gRPC uses Protocol Buffers (protobuf), a binary and compact data serialization format, resulting in faster and more efficient communication. In contrast, REST APIs use JSON, which is human-readable but bulkier than Protocol Buffers, impacting performance.
gRPC, generally offers better performance compared to REST due to the use of binary serialization, HTTP/2 features, and efficient handling of streaming.
That being said, gRPC and REST have two different use cases. gRPC with Protocol Buffers excels in high-performance microservices and real-time apps, while REST APIs with JSON are ideal for standard CRUD operations and public-facing interfaces.
Getting started with Golang & gRPC
To install golang on macOs with brew, run this.
brew install go
For other Operating Systems, refer here for installation. https://go.dev/doc/install
Set $GOROOT and $GOPATH. For homebrew installations, path looks different.
export GOROOT=/opt/homebrew/Cellar/go/1.20.6/libexecexport PATH=$PATH:$GOROOT/binexport GOPATH=$PATH:$GOROOT/bin
Run this command to verify the installation.
go version
Install protobuf and related tools.
brew install protobuf
brew install protoc-gen-go-grpcbrew install protoc-gen-go
Create your first project with Golang and gRPC
We will be creating a golang gRPC server and a method that returns “hello world”
Create a proto filehello_world.proto
syntax = "proto3";
option go_package = "/pb";
service HelloWorldService {
rpc Greeting(HelloWorldServiceRequest) returns (HelloWorldServiceReply) {}
}
message HelloWorldServiceRequest {
string name = 1;
}
message HelloWorldServiceReply {
string message = 2;
}
Run the protoc compiler.
protoc *.proto --go_out=./ --go-grpc_out=./
go_out flag in protoc specifies the directory where the generated Go code should be placed after compiling the ProtoBufs.
go-grpc_out option specifies the directory where the gRPC service code should be generated in Go.
With this, _grpc.pb.go and pb.go file should be generated.
A interface will be generated in the _grpc.pb.go file.
type HelloWorldServiceClient interface {
Greeting(ctx context.Context, in *HelloWorldServiceRequest, opts ...grpc.CallOption) (*HelloWorldServiceReply, error)
}
Create a server struct and implement the interface method.
type server struct {
pb.HelloWorldServiceServer
}
func (s *server) Greeting(ctx context.Context, req *pb.HelloWorldServiceRequest) (*pb.HelloWorldServiceReply, error) {
return &pb.HelloWorldServiceReply{
Message: fmt.Sprintf("Hello, %s", req.Name),
}, nil
}
Register the gRPC server with this line.
pb.RegisterHelloWorldServiceServer(s, &server{})
Finally, the main.go will look like this.
package main
import (
"context"
"fmt"
"golang-grpc/pb"
"log"
"net"
"google.golang.org/grpc"
)
type server struct {
pb.HelloWorldService
}
func (s *server) Greeting(ctx context.Context, req *pb.HelloWorldServiceRequest) (*pb.HelloWorldServiceReply, error) {
return &pb.HelloWorldServiceReply{
Message: fmt.Sprintf("Hello, %s", req.Name),
}, nil
}
func main() {
fmt.Println("start grpc server")
listener, err := net.Listen("tcp", ":8080")
if err != nil {
panic(err)
}
s := grpc.NewServer()
pb.RegisterHelloWorldServiceServer(s, &server{})
if err := s.Serve(listener); err != nil {
log.Fatalf("failed to serve: %v", err)
}
}
You can find the entire project in github here.
References:
Readers,
Thank you for reading.
For any queries, reach me at chayanikamisra1997@gmail.com
Twitter: https://twitter.com/misra_chayanika
Thank you!!
Recent Posts
See AllWhat is Couch DB? Couch DB is a Document DB. Documents DBs are a class of NoSQL databases built around JSON-like documents which are...
Design a News Feed service to quickly generate and fetch the news feed and profile feed for each user present in the social network....
Comentários