Lately I have been playing with go-kit to try to understand how I can use it to build microservices. There are a variety of examples available here, but unfortunately, not all of them are well documented.

I specifically wanted to figure out how to use the Api Gateway example, so I did. Here is how I got it working….

You will need to have a working Go environment setup to follow along. You can get that going by starting here.

Getting the source code

Download the go-kit examples by go get’ing the repo somewhere on your local system:

Starting Addsvc

Cd into the addsvc example directory (this is assuming your $GOHOME is set to $HOME/go), then fetch the dependencies:

Now we start the service:

The only port that we will actually use is: -grpc-addr :7082, this is the port we will register with Consul.

This service exposes 2 endpoints: /sum (this returns the sum of the 2 received values) and /concat (this returns the concatenation of the 2 received values).

Lets try it out by sending a request to each of the endpoints to make sure it is working:

Starting Stringsvc

We will now start a second example service. Open a new terminal, cd into the stringsvc3 example directory, fetch dependencies, then run the service:

This service exposes 2 endpoints: /count (this returns a count of letters in the received string) and /uppercase (this returns an uppercase version of the received string).

Lets try it out by sending a request to each of the endpoints to make sure it is working:

Starting Consul

First, you need to download Consul for your specific OS/architecture here.

Next, you should create a file that will be used to register each of the previously started services (addsvc and stringsvc) with Consul. Open a new terminal, then in the same directory that you downloaded Consul run:

Now we will run Consul and specify the path to the directory that we just created:

You should be able to see addsvc and stringsvc as a registered services in Consul by browsing to http://localhost:8500/ui/dc1/services

For more info on registering Consul services, check this out.

Starting Api Gateway

Now that we have Consul running and all of our services registered with Consul, we can make use of the Consul api by running the apigateway go-kit example. The Api Gateway pattern is meant to be used to create a single entry point for requests that will be handled by a variety of services. You can read more about it here. This is what the apigateway example will do for us.

Open a new terminal, then run the following to start the apigateway service:

Now, lets try out the same endpoints that we tested earlier for each of our services, but using the apigateway server:

Cool! The requests were proxied to the appropriate locations based upon the value immediately following the port number (/stringsvc and /addsvc).

For more info on go-kit, checkout