REST API example using GoLang and Gorilla mux

I created a simple REST API, accepting and responding JSON in GO and using a library for handling the requests, which is named Gorilla/mux.

Tomas F. Lingotti
2 min readAug 1, 2019

H i folks, this is a pretty straight forward API, but is also a good entry point to dig into golang web-world.

So first of all, I used a slice as an in memory database (in the next article I suppose that a real DB is going to take place) and wrote a model struct with some methods to interact with the slice.

The main structure is like this:

Here you can see the struct and some basic methods to operate over the dummy DB.

Now, the handlers to use these methods.
Create:

This is a basic handler for HTTP. The response writer is in charge of the response (oh no!) and the request, of course the incoming part from the client. So from here we can grab the body, params, headers, etc.

The GET by serial number API:

With MUX, it is easy to get the map of param name / param value (as a map), and then, some basic logic to transform the incoming string into a int64.

Finally, the update API:

And you can find the rest of the code here.

Conclusion:

Gorilla Mux is a good library (not a framework) for doing http routing. If you are planning a whole micro service architecture, I strongly recommend to use other lib instead. There are many options out of there, my little suggestion is go-kit which encourage a lot of good practices like clean architecture.

Keep using go, the next tutorial will be about go and elastic search!

By folks!

--

--