Playing Around with Go

June 01, 2014

I’ve been interested recently with using Golang thanks to a few friends of mine who have been raving about how good it is. I’ve tried it before through their interactive console, Golang tour. After that, I’ve proceeded reading around the documentation. And I find the documentation quite comprehensive.

Last week, I was discussing a possible project I wanted to start with my friend. I thought it would be interesting to use Go to create the API for this. Prior to starting this project, we’ve decided to play around with the languages we plan to use. I was assigned the backend component and decided to use Golang for it. I wanted to create a simple API so that I will be able to explore the following areas:

Create an HTTP endpoint

Create DB migrations

Map the db to structs

Handle dependency management

Testing (which I am still figuring out as of writing)

It proved out to be quite simpler than I imagined.

Create an HTTP endpoint

The first thing I did was to figure out a way to make it run, and see something printed out on my browser which is the first goal.

To create the HTTP endpoint, I’ve decided to use gorilla-mux. You need to go to $GOPATH/src/github.com/user/simple-api-go. Create a file named simple_api.go. Make sure to install gorilla-mux first before you run this.

Once you save this, run go build. This will generate an executable file simple_api_go in the main folder. Simply run this, and go to localhost:3000. You should be able to see ‘hello world’.

Create DB migrations

The next step is to see how I’ll be able to manage DB migrations in this project. I was googling around a possible library to use. I ended up using Goose. Once you have this installed, create a database for simple-api-go. Create db/dbconf.yml in your simple-api-go and fill it in with the necessary information. I am currently using MySQL. Myd dbconf.yml looks something like this:

After that, run goose up. This will run the script above. The database you have created should now have the the posts table. Read more about goose here.

Map the db to structs

Now, I needed to find out a way to easily access the info from the database. To do this, I’ve decided to use gorp. First thing you need to do is update simple_api.go and create a struct Post with the gorp annotations.