Exploring which language and framework to choose for a new microservice? Golang and gRPC could be the perfect pairing. Here's why they work so well together, plus a step-by-step guide to getting started from scratch.
In short, Golang's low memory footprint, fast execution, and concurrency features make it an excellent choice for scalable microservices.
That said, they suit different cases. gRPC with Protocol Buffers excels in high-performance microservices and real-time apps, while REST with JSON is ideal for standard CRUD operations and public-facing interfaces.
Install Go on macOS with Homebrew, set your paths, and verify:
brew install go export GOROOT=/opt/homebrew/Cellar/go/1.20.6/libexec export PATH=$PATH:$GOROOT/bin go version
Then install Protocol Buffers and the related tools:
brew install protobuf brew install protoc-gen-go-grpc brew install protoc-gen-go
We'll build a gRPC server with a method that returns "hello world". Start with a proto file, hello_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 to generate the Go and gRPC code:
protoc *.proto --go_out=./ --go-grpc_out=./
This generates _grpc.pb.go and pb.go. Create a server struct, implement the interface method, register it, and start listening. The full main.go:
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)
}
}
That's a complete, working gRPC server in Go. The full project is on my GitHub, and the official Go and gRPC docs are great next steps. Happy building.