GO’s Beego Framework: Creating a web that connects to MySQL

This tutorial is intended for developers new to GO and the Beego framework (http://beego.me/). You’ll learn how to create a very simple web app that connects to a MySQL database.

Installing & running Beego

You’ll first need to download Beego, from your command line:

cd ${GOPATH}/src

go get github.com/astaxie/beego
go get github.com/beego/bee

Create a new Beego project by typing:

Linux users, create a link of the bee utility in your /usr/bin/ folder:

ln -s ${GOPATH}/bin/bee /usr/bin/bee

bee new beegomysql

src $ bee new beegomysql
[INFO] Creating application…
/Users/antonimassomola/golang/src/beegomysql/
/Users/antonimassomola/golang/src/beegomysql/conf/
/Users/antonimassomola/golang/src/beegomysql/controllers/
/Users/antonimassomola/golang/src/beegomysql/models/
/Users/antonimassomola/golang/src/beegomysql/routers/
/Users/antonimassomola/golang/src/beegomysql/tests/
/Users/antonimassomola/golang/src/beegomysql/static/
/Users/antonimassomola/golang/src/beegomysql/static/js/
/Users/antonimassomola/golang/src/beegomysql/static/css/
/Users/antonimassomola/golang/src/beegomysql/static/img/
/Users/antonimassomola/golang/src/beegomysql/views/
/Users/antonimassomola/golang/src/beegomysql/conf/app.conf
/Users/antonimassomola/golang/src/beegomysql/controllers/default.go
/Users/antonimassomola/golang/src/beegomysql/views/index.tpl
/Users/antonimassomola/golang/src/beegomysql/routers/router.go
/Users/antonimassomola/golang/src/beegomysql/tests/default_test.go
/Users/antonimassomola/golang/src/beegomysql/main.go
2016/06/14 09:07:57 [SUCC] New application successfully created!

Beego creates some default folders and files following the MVC architecture pattern (Figure 1).

Figure 1

cd beegomysql

Run the project using Beego’s bee utility:

bee run watchall

beegomysql $ bee run watchall
bee :1.4.1
beego :1.6.1
Go :go version go1.5.3 darwin/amd64

2016/06/14 09:19:20 [INFO] Uses ‘beegomysql’ as ‘appname’
2016/06/14 09:19:20 [INFO] Initializing watcher…
2016/06/14 09:19:20 [TRAC] Directory(/Users/antonimassomola/golang/src/beegomysql/controllers)
2016/06/14 09:19:20 [TRAC] Directory(/Users/antonimassomola/golang/src/beegomysql)
2016/06/14 09:19:20 [TRAC] Directory(/Users/antonimassomola/golang/src/beegomysql/routers)
2016/06/14 09:19:20 [TRAC] Directory(/Users/antonimassomola/golang/src/beegomysql/tests)
2016/06/14 09:19:20 [INFO] Start building…
2016/06/14 09:19:24 [SUCC] Build was successful
2016/06/14 09:19:24 [INFO] Restarting beegomysql …
2016/06/14 09:19:24 [INFO] ./beegomysql is running…
2016/06/14 09:19:24 [asm_amd64.s:1721][I] http server Running on :8080

Project is running on localhost port 8080. Open your web browser and enter the following URL http://localhost:8080. If everything worked as expected you should see the “Welcome to Beego” page (Figure 2).

Figure 2

The bee utility logs every petition received:

2016/06/14 09:20:17 [router.go:829][D] | GET | / | 7.355621ms | match | / |

Building our first Beego web app

Beego’s default controller is located in controllers/default.go. By default Beego creates the Get method (Figure 3). This method is used to output the data you see when opening the http://localhost:8080 URL. Beego sends data to the template by assigning it to this.Data (map[string]interface{}).

Figure 3
Try passing a new value to the template by adding the following code:

c.Data["Test"] = "Test string"

Now open the index.tpl template file (views/index.tpl) and add the following code:

Test Data: {{.Test}}

bee automatically detects any change in the source code of the project and rebuilds it so you don’t need to worry about recompiling. Go back to your browser and refresh the page, you should see the “Test string” being passed to the template.

Let’s create a new router to test how to create new routes in our web app. Open the default routing file (routers/router.go). Add the following code below the main route:

beego.Router("/user/register/:username", &controllers.MainController{}, "get:UserRegister")

The first argument is the path, the second is the controller and the third is the method called when accessing that URL (http://localhost:8080/user/register/antonimassomola). We can define the methods we support, in our case we only accept GET petitions.

We must now create the UserRegister method in our controller’s file (controllers/default.go):

func (c *MainController) UserRegister() {

    c.Data["username"] = c.Ctx.Input.Param(":username")
    c.TplName = "register.tpl"

}

We’ll read the :username parameter being passed in the URL and load the register template.

The register template file must be created (views/register.tpl):

Username: {{.username}}

Go back to your browser and enter this URL: http://localhost:8080/user/register/your_username. You should see the register template being rendered with the username parameter being read from the URL.

We will be using MySQL as our relational database. Go to your console and type the following to install the MySQL GO driver: go get github.com/go-sql-driver/mysql

Create a database named beegomysql:

create database beegomysql;
use beegomysql;

Create a new table and name it users:

create table users(id int(3) primary key auto_increment, username varchar(64));

Go back to your IDE (Sublime, WebStorm, etc.) and edit the main.go file. You’ll need to import the following files:

_ "beegomysql/models"
_ "github.com/go-sql-driver/mysql"
"github.com/astaxie/beego/orm"

The init() funciton is needed to register the MySQL driver and database:

func init() {
    orm.RegisterDriver("mysql", orm.DRMySQL)
    orm.RegisterDataBase("default", "mysql", "beego:beego@tcp(172.26.0.20:3306)/beegomysql?charset=utf8")
}

By default there is no models.go file created, so you’ll need to create one manually inside the models folder:

package models

import (
    "github.com/astaxie/beego/orm"
)

func AddUser(username string) (error) {

    o := orm.NewOrm()
    o.Using("default")

    err := o.Raw("INSERT INTO users SET username = ?", username).QueryRow()

    return err

}

We now need to import the models file in our controller:

"beegomysql/models"

We must edit our UserRegister() function:

func (c *MainController) UserRegister() {

    username := c.Ctx.Input.Param(":username")

    err := models.AddUser(username)

    c.Data["Username"] = username
    c.Data["Result"] = false

    if(err == nil){
        c.Data["Result"] = true
    }

    c.TplName = "register.tpl"

}

Finally we must edit our register.tpl template to inform if the user has been added to the users table:

Username: {{.Username}}
<br>
Result: {{.Result}}

Conclusion

Building web apps with GO’s Beego framework is easy and fast. Beego has a lot of functionality (http://beego.me/docs/intro/) and is one the fastest GO frameworks (http://www.techempower.com/benchmarks/#section=data-r6&hw=i7&test=json).

You can download the project at: github.com/antonimassomola/beegomysql