Go Kit (2) – Go kit design is well-suited for both microservices and elegant monoliths.

https://gokit.io/faq/

Architecture and design

Introduction — Understanding Go kit key concepts

If you’re coming from Symfony (PHP), Rails (Ruby), Django (Python), or one of the many popular MVC-style frameworks out there, the first thing you should know is that Go kit is not an MVC framework. Instead, Go kit services are laid out in three layers:

  1. Transport layer
  2. Endpoint layer
  3. Service layer

Requests enter the service at layer 1, flow down to layer 3, and responses take the reverse course.

This may be a bit of an adjustment, but once you grok the concepts, you should see that the Go kit design is well-suited for modern software design: both microservices and so-called elegant monoliths.

Transports — What are Go kit transports?

The transport domain is bound to concrete transports like HTTP or gRPC. In a world where microservices may support one or more transports, this is very powerful; you can support a legacy HTTP API and a newer RPC service, all in a single microservice.

When implementing a REST-ish HTTP API, your routing is defined within a HTTP transport. It’s most common to see routes defined in a HTTP Router function like this:

r.Methods("POST").Path("/profiles/").Handler(httptransport.NewServer(
		e.PostProfileEndpoint,
		decodePostProfileRequest,
		encodeResponse,
		options...,
))

Endpoints — What are Go kit endpoints?

An endpoint is like an action/handler on a controller; it’s where safety and antifragile logic lives. If you implement two transports (HTTP and gRPC), you might have two methods of sending requests to the same endpoint.

Services — What is a Go kit service?

Services are where all of the business logic is implemented. A service usually glues together multiple endpoints. In Go kit, services are typically modeled as interfaces, and implementations of those interfaces contain the business logic. Go kit services should strive to abide the Clean Architecture or the Hexagonal Architecture. That is, the business logic should have no knowledge of endpoint- or especially transport-domain concepts: your service shouldn’t know anything about HTTP headers, or gRPC error codes.

Middlewares — What are middlewares, in Go kit?

Go kit tries to enforce a strict separation of concerns through use of the middleware (or decorator) pattern. Middlewares can wrap endpoints or services to add functionality, such as logging, rate limiting, load balancing, or distributed tracing. It’s common to chain multiple middlewares around an endpoint or service.

Design — How is a Go kit microservice modeled?

Go kit service diagram

Putting all these concepts together, we see that Go kit microservices are modeled like an onion, with many layers. The layers can be grouped into our three domains. The innermost service domain is where everything is based on your specific service definition, and where all of the business logic is implemented. The middle endpointdomain is where each method of your service is abstracted to the generic endpoint.Endpoint, and where safety and antifragile logic is implemented. Finally, the outermost transport domain is where endpoints are bound to concrete transports like HTTP or gRPC.

You implement the core business logic by defining an interface for your service and providing a concrete implementation. Then, you write service middlewares to provide additional functionality, like logging, analytics, instrumentation — anything that needs knowledge of your business domain.

Go kit provides endpoint and transport domain middlewares, for functionality like rate limiting, circuit breaking, load balancing, and distributed tracing — all of which are generally agnostic to your business domain.

In short, Go kit tries to enforce strict separation of concerns through studious use of the middleware (or decorator) pattern.

Micro-services Using Go-kit: REST Endpoint

Powered by Google TranslateTranslate

In this article, I will create a simple micro-service using Go programming language and go-kit as a standard micro-services library. The service will be exposed via REST endpoint.

Sharing is caring!

Micro-services

In the today’s world, the micro-services architecture has gain its popularity. I will not explain what is micro-services architecture in particular, since there are lots of sites on the internet already discussed about this. However, I will give two good websites regarding micro-service.

Firstly from one of my favorite, Martin Fowler. You can see his amazing explanation here. And the other one is from microservices.io. There are many good articles inside talking about pattern and examples.

Go-lang

golangGo is an open source programming language that makes it easy to build simple, reliable, and efficient software¹.

The language is designed by Google and intended to solve Google’s problems. So one can hope that this language work on a scale, for large programs and dependencies.

Go-kit

go-kit

Go-kit really helps for simplifying in terms of building micro-services architecture. This is  because it has so many features, such as service connectivity, metrics and logging. Therefore I would like to say a special thanks for Peter Bourgon (@peterbourgon) and all the contributors for providing this awesome libraries.

 

Use Case

My focus in this article is exposing REST endpoint as a service. The service itself will expose the endpoint with HTTP POST method. And then it will return lorem ipsum message within JSON format.

The endpoint URL format will be /lorem/{type}/{min}/{max}, with several descriptions:

  1. type will be a lorem type, which are word, sentence and paragraph.
  2. min and max will be at least minimum letters and at most maximum letters for generator.

Note: I assume your GOPATH already set in the environment variables

Step-by-step

Before starting the step-by-step, there are several libraries which are needed for this examples. Those are:

  1. go-kit libraries.
  2. golorem libraries: for generating lorem ipsum text
  3. gorilla mux libraries: for http handler
Step 1: Building the Service

For whatever coolest tools you have, you need to create business logic at a first time. Our business logic is, as stated in the use case, to create lorem ipsum text, based on word, sentence or paragraph. So let’s create lorem folder under your workspace. In my case, my folder is $GOPATH/github.com/ru-rocker/gokit-playground/lorem. Then create file service.gounder the folder and add the following code:

Now we have already the interface. However, interface means nothing without methods implementation. To service.go, add following implementations:

Notice that I am using golorem functions for each method implementations. 

Step 2: Modeling Request and Response

Because this service is part of HTTP, therefore the next step is modeling request and response. If you look back to the Use Case, you will find there are three properties required for the implementation. Those are type, min and max.

And for the response itself, we only need two fields. Those fields are message that contains lorem ipsum text. The other one is error field, which will give error description whenever there is an error. So, let’s create another file, and give it a name endpoints.go and add the following code:

Step 3: Creating Endpoints

Endpoint is a special function in go-kit because you can wrap it into http.Handler. In order to make our service function turns into endpoint.Endpoint function, we are going to make a function to handle the LoremRequest, do some logic inside, then return the LoremResponse. To endpoints.go, add following code:

Step 4: Transport

Before handling the http request and response, at first we need to create encoder and decoder from struct to json or the other way around. For this purpose, create new file, give it a name transport.go and add following code:

Once you already declare the encoder and decoder  functions, then it is time to create the http handler. To transport.go, add following code:

Note: take a look at line 15. It is the way to describe the URL path and HTTP request method.

Step 5: Main

So far we already have service/business layer, endpoint and transport for our services. After all set, it is time to create the main function. The main function basically structure the endpoint and make it available into HTTP transport.

So, under the lorem folder, create another folder, named it lorem.d. The dot d means daemon. You can name it as you like it. I prefer this one. Then create file main.go, and add following code:

Step 6: Run the Example

It is time to run the example. Open your shell and type:

Test the endpoint by using curl or postman. And you will see similar results:

Screen Shot 2017-02-17 at 2.45.35 PM
Sample lorem services

Sample Code

That’s it. Whenever you have any interest about this article and willing to know more, you can check on my github.

See ya.

Author: ru rocker

I am a professional software developer with more than 10 years experiences. I am a certified Java Developer (SCJP and SCWCD). However, In the recent months, I have more interest in DevOps and start to become a polyglot developer. Python and Go-lang become my favorite programming languages besides Java.

Leave a Reply

Your email address will not be published. Required fields are marked *