Building a Web Application with Martini and Gorm - Part 1


Martini is a very powerful Go framework, and it will enable you to launch applications very quickly. Gorm is an ORM for Go, enabling you to run queries against a MySQL database very quickly. We’re going to briefly go over Martini and Gorm in this first part, and the basic structure of the application.


To start off, your first file will be server.go, it will look like the following:

package main

import (
    _ ""

var (
    db            gorm.DB
    sqlConnection string

func main() {
    var err error

    sqlConnection = "doug:[email protected]("

    db, err = gorm.Open("mysql", sqlConnection)

    if err != nil {

    m := martini.Classic()

    m.Get("/", func(r render.Render) {
        var retData struct {
            Items []Item


        r.HTML(200, "index", retData)

Let’s Break This Down


The first import is the main martini package, this is required to load the martini framework.

The next two lines are required by gorm to communicate with MySQL.

The last import is an easy middlware to help render HTML, XML or JSON responses to the client. We will use this to easily output our data.


The easiest way for me to handle passing around the db gorm connection, and the sqlConnection string. You will see later why we did this, first being different controllers will need to communicate with the same db resource, and second being when we push our application to Heroku, to communicate with ClearDB which is a Heroku add-on, we need to make some modifications.

func main()

Here’s the mean and bones of our application. The first, we are setting the err variable since we need to access the global db variable but just need to use the local err variable.

The second part, we are setting the connection string to communicate with MySQL. To break it down:

username:[email protected](host)/table?additional connection params

You will need to change this according to your setup. I would recommend you do not hard code your connection strings in your application, but use a method to load a config file separate of the binary, or read environment variables on the machine.

The next few lines are pretty straight forward, we are connecting to our database, and checking to see if there were any initial errors. We will build upon this later.

The last part of this function shows the Martini specific code. The first is to set up the m variable to control different parts of martini. The second part we are loading the render middleware so our controllers can access it. The third part is our first basic controller.


Typically I start with a retData variable, this helps me organize what I’m going to send to the view. In this case, I’m only going to return a list of items we fetch from the database.

db.Find is a basic gorm command, it’s simply going to run SELECT * FROM items since we are not chaining any other commands.

r.HTML is what martini will use to render the view. 200 is the response code, “index” is the name of the template file, and retData is the variable we created at the top of this controller.

Finally, we have m.Run() which loads up Martini. Now that we have the basic server code set up, lets move onto the struct which will assist gorm into working correctly.


package main

type Item struct {
    Id int64
    Title string
    Description string
    UserName string

This is a very small file (for now). What we are doing is maping out the database structure, Id will be the primary key we set in the database. Go suggests that we would actually use ID, but Gorm would read that as trying to find the i_d column, this is a bug that hasn’t been resolved yet, so unfortunately we need to keep it as Id to keep things simple.

Title, Description and UserName are pretty straightforward. Gorm will look for the title, description and user_name columns in the items table.

Note: When creating your database, it’s best to make sure you don’t let columns have null values, you may run into some issues with Gorm

Let’s move onto the template.


To preface, you could name the file index.tmpl or index.html, the middleware will search for both file names, and this can be customized if need be.

Note: Be sure this file is in a new templates directory you will create in your project directory

<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <title>martini gorm example</title>
    {{ range .Items }}
    <h3>{{ .Title }}</h3>
    <p>{{ .Description }}</p>
    <p>By: {{ .UserName }}</p>
    {{ else }}
    <p>No items found!</p>
    {{ end }}

Next Steps

Now, in your favorite MySql client, enter in a few records for the title, description and user_name.

Then, make sure you are in your project root directory and run in the terminal/command prompt go run *.go (I would also recommend gin for hotreloading your code, not to be confused with a web framework similar to Martini)

Up next, we will look into the Martini middlewares: binding and XSRF while also handling POST HTTP requests, and expanding our use of Gorm. Continue onto Part 2 now!

Last Updated: 2015-01-21 06:54:03 +0000 UTC

What are your thoughts on this?


RSS feed

Follow Doug On Social