Microservice with go-kit Part II

Tram Ho

In part I we’ve learned the concept of how Microservice worked and also how Go Kit fit into the design. In this part lets put it into practice by implementing a simple random sentence generator service.

Service

Lets start from our business logic by define and implement a service, basically a contract. For the purpose of this example our service will has one simple method which take n number of setences to return and return n random setences.

Endpoint

Our endpoint will wrap the sentences return from service into a SentencesResponse struct with Data and Err field. Because could only come from client bad input we will only wrap error in the return struct so that we can feedback to the client what kind error that make the server failed. We also wrap our endpoint in a loggingMiddleware, which take a logger and an endpoint and return a new endpoint decorated with logging behaviour.

HTTP Transport

To expose our service to the ourside world, we choose HTTP protocol as our transport. The number of sentences to return will be get in the form of request body from a POST request and when we get the result back from endpoint we write a JSON response back to the client. The conversion and type checking is to get user generated error, which we wrapped inside SentencesResponse struct, and show it accordingly. Any error that return from endpoint will be caught by ServerErrorEncoder server option.

Wire it up

This is how we wired up all component together to get a working service. There is nothing fancy here, just a couple of initialization code.

Conclusion

I hope from this post you will get a better idea on how to implement a microservice in golang using Go Kit packages.

Share the news now

Source : Viblo