Introduction to Microservices, Go-Kit, Grpc. Golang

Edwin Siby
3 min readJul 8, 2023

Introduction to Microservices

Microservices is an architectural style that structures an application as a collection of small, loosely coupled services. Each service is responsible for a specific business capability and communicates with other services through well-defined APIs.

Go Toolkit (GoKit) is a popular toolkit for building microservices in Go. It provides a set of libraries, patterns, and utilities to simplify the development of scalable, modular, and maintainable microservices.

Introduction to gRPC

gRPC is a high-performance, open-source framework for remote procedure calls (RPC). It uses Protocol Buffers (protobuf) as the interface definition language and supports various programming languages, including Go. gRPC enables communication between microservices using a strongly-typed contract, allowing for efficient and reliable service-to-service communication.

Sample Project 1: Building a Microservice with GoKit

In this sample project, we’ll create a simple microservice using GoKit. The microservice will expose an HTTP endpoint to perform CRUD operations on a resource. We’ll use GoKit’s middleware and transport libraries for handling requests and responses.

Start by setting up a new Go project and initializing Go modules:

$ mkdir go-kit-sample 
$ cd go-kit-sample
$ go mod init github.com/your-username/go-kit-sample

Install the required dependencies:

$ go get github.com/go-kit/kit/v2

Create a file named main.go and add the following code:

package main

import (
"encoding/json"
"fmt"
"net/http"

"github.com/go-kit/kit/log"
"github.com/go-kit/kit/transport"
)

type Resource struct {
ID int `json:"id"`
Name string `json:"name"`
}

func main() {
logger := log.NewJSONLogger(log.NewSyncWriter(os.Stdout))

http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
// Handle requests and responses here
})

fmt.Println("Listening on http://localhost:8080")
http.ListenAndServe(":8080", nil)
}

Implement the CRUD operations inside the / handler:

http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "GET":
// Retrieve all resources
json.NewEncoder(w).Encode(resources)
case "POST":
// Create a new resource
var resource Resource
err := json.NewDecoder(r.Body).Decode(&resource)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
resources = append(resources, resource)
w.WriteHeader(http.StatusCreated)
default:
w.WriteHeader(http.StatusMethodNotAllowed)
}
})

Run the microservice:

$ go run main.go

Congratulations! You have created a simple microservice using GoKit. You can test the endpoints using a tool like cURL or Postman.

Sample Project 2: Creating a gRPC Server and Client

In this sample project, we’ll create a gRPC server and client using Go. The server will provide a “Hello World” service, and the client will make a request to the server to get the response.

Create a new directory for the project and navigate into it:

$ mkdir grpc-sample 
$ cd grpc-sample

Initialize Go modules:

$ go mod init github.com/your-username/grpc-sample

Install the required dependencies:

$ go get google.golang.org/grpc $ go get github.com/golang/protobuf/protoc-gen-go

Create a new file named hello.proto and add the following protobuf definition:

syntax = "proto3";

service HelloService {
rpc SayHello (HelloRequest) returns (HelloResponse) {}
}

message HelloRequest {
string name = 1;
}

message HelloResponse {
string message = 1;
}

Generate Go code from the protobuf definition:

$ protoc --go_out=plugins=grpc:. hello.proto

Create a file named server.go and implement the gRPC server:

package main

import (
"context"
"log"
"net"

"google.golang.org/grpc"
)

type server struct{}

func (s *server) SayHello(ctx context.Context, req *HelloRequest) (*HelloResponse, error) {
return &HelloResponse{Message: "Hello, " + req.Name}, nil
}

func main() {
lis, err := net.Listen("tcp", ":50051")
if err != nil {
log.Fatalf("failed to listen: %v", err)
}
s := grpc.NewServer()
RegisterHelloServiceServer(s, &server{})
if err := s.Serve(lis); err != nil {
log.Fatalf("failed to serve: %v", err)
}
}

Create a file named client.go and implement the gRPC client:

package main

import (
"context"
"log"

"google.golang.org/grpc"
)

func main() {
conn, err := grpc.Dial("localhost:50051", grpc.WithInsecure())
if err != nil {
log.Fatalf("did not connect: %v", err)
}
defer conn.Close()
c := NewHelloServiceClient(conn)

name := "John"
res, err := c.SayHello(context.Background(), &HelloRequest{Name: name})
if err != nil {
log.Fatalf("could not greet: %v", err)
}
log.Printf("Response: %s", res.Message)
}

Run the gRPC server:

$ go run server.go

In a separate terminal, run the gRPC client:

$ go run client.go

You should see the response message “Hello, John” printed in the client’s terminal. Congratulations! You have created a simple gRPC server and client using Go.

I hope this helps you get started with microservices, GoKit, and gRPC.Have a nice day GOPHERS.

--

--