Writing Your First Microservice in Go with gRPC

Satyam SinghSatyam Singh
3 min read

Introduction

Microservices have become a standard architecture for building scalable applications. If you are new to microservices and Go, this guide will take you from zero to a working gRPC-based microservice. By the end, you will have a functional Go microservice that performs simple addition via gRPC.

Prerequisites

Before we start, ensure you have the following installed on your system:

  • Go (Download from Go Official Site)

  • Protocol Buffers (protoc) (Download from Protocol Buffers GitHub)

  • Go plugins for Protobuf:

      go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
      go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest
    

Step 1: Setting Up the Project

  1. Create a project directory:

     mkdir microservice-example
     cd microservice-example
    
  2. Initialize a Go module:

     go mod init github.com/yourusername/microservice-example
    

Step 2: Defining the gRPC API

  1. Create a proto/ directory:

     mkdir proto
    
  2. Create proto/adder.proto and define the service:

     syntax = "proto3";
    
     package proto;
     option go_package = "github.com/yourusername/microservice-example/proto";
    
     service Adder {
       rpc Add (AddRequest) returns (AddResponse);
     }
    
     message AddRequest {
       int32 A = 1;
       int32 B = 2;
     }
    
     message AddResponse {
       int32 Result = 1;
     }
    

Step 3: Generating Go Code from Proto File

Run the following command to generate the necessary Go files:

protoc --go_out=. --go_opt=module=github.com/yourusername/microservice-example \
  --go-grpc_out=. --go-grpc_opt=module=github.com/yourusername/microservice-example \
  proto/adder.proto

This generates adder.pb.go and adder_grpc.pb.go in the proto/ directory.

Step 4: Implementing the gRPC Server

  1. Create server.go and add the following code:

     package main
    
     import (
       "context"
       "fmt"
       "log"
       "net"
       "google.golang.org/grpc"
       pb "github.com/yourusername/microservice-example/proto"
     )
    
     type AdderServer struct {
       pb.UnimplementedAdderServer
     }
    
     func (s *AdderServer) Add(ctx context.Context, req *pb.AddRequest) (*pb.AddResponse, error) {
       result := req.A + req.B
       return &pb.AddResponse{Result: result}, nil
     }
    
     func main() {
       listener, err := net.Listen("tcp", ":50051")
       if err != nil {
         log.Fatalf("Failed to listen: %v", err)
       }
       server := grpc.NewServer()
       pb.RegisterAdderServer(server, &AdderServer{})
       fmt.Println("gRPC Server is running on port 50051...")
       if err := server.Serve(listener); err != nil {
         log.Fatalf("Failed to serve: %v", err)
       }
     }
    

Step 5: Implementing the gRPC Client

  1. Create client.go and add the following code:

     package main
    
     import (
       "context"
       "fmt"
       "log"
       "google.golang.org/grpc"
       pb "github.com/yourusername/microservice-example/proto"
     )
    
     func main() {
       conn, err := grpc.Dial("localhost:50051", grpc.WithInsecure())
       if err != nil {
         log.Fatalf("Could not connect: %v", err)
       }
       defer conn.Close()
       client := pb.NewAdderClient(conn)
       req := &pb.AddRequest{A: 5, B: 3}
       res, err := client.Add(context.Background(), req)
       if err != nil {
         log.Fatalf("Error calling Add: %v", err)
       }
       fmt.Printf("Sum: %d\n", res.Result)
     }
    

Step 6: Installing Dependencies

Ensure all dependencies are installed by running:

go mod tidy
go get google.golang.org/grpc
go get google.golang.org/protobuf

Step 7: Running the Microservice

  1. Start the gRPC server:

     go run server.go
    

    Expected output:

     gRPC Server is running on port 50051...
    
  2. Run the client in a new terminal:

     go run client.go
    

    Expected output:

     Sum: 8
    

Conclusion

If you found this guide useful, consider starring the project on GitHub: GitHub Repository. Your support helps improve and maintain this project!

Stay connected with me:

10
Subscribe to my newsletter

Read articles from Satyam Singh directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Satyam Singh
Satyam Singh

wanted to write more than just code