From Rails to Go

A recent project at work required a high performance API and a light-weight front end. I’ve been looking for an opportunity to explore other languages and frameworks and this seemed like a perfect opportunity. We already have a few services written in Go, so I decided to start there.

The Go Programming Language is a “fast, statically typed, compiled language.” In other words, very different from Ruby (which is dynamically typed and interpreted). In Ruby, everything is an object; Go doesn’t have classes. Yes, very different.

Web

With my choice of programming language set, it was time to find a web framework. After a bit of Googling, I came upon Gin. It promises “performance and productivity” which is exactly what I needed.

Gin features a very fast router for processing requests as well as easy rendering of responses in JSON or HTML. Gin uses the html/template package for rendering dynamic HTML pages (also see text/template for complete documentation).

Database

The next step was database access. I typically work with Active Record, so I started searching for something similar. GORM is an ORM Library in Go. It is full-featured (almost) and developer friendly. Its API is similar to Active Record and it supports all of the features I need including a PostgreSQL driver.

Creating models is easy using GORM. Define the model as a Go struct and include gorm.Model to add ID and timestamp columns. Then pass the model to db.AutoMigrate and GORM will create a table with the required columns automagically. The migration doc has examples of automatic and manual migrations.

Miscellaneous

Since I plan on eventually deploying this application to Heroku, and Heroku uses an environment variable for the DATABASE_URL, I’m also using the Go port of Ruby’s dotenv project named godotenv to load environment variables in development.

Sample App

I posted a complete sample application named goweb on GitHub. Feel free to clone that repo as a starting point for your own creations. The README file includes instructions for setting everything up on a Mac with Homebrew.