xesite/blog/beego-2014-11-28.markdown

2.7 KiB

title date tags
Web Application Development with Beego 2014-11-28
go
beego

Beego is a fantastic web application framework from the Go China community. It currently powers some of the biggest websites in China, and thus the world.

Let's get started. For now I am going to assume you are running OSX or Linux. Getting Beego set up on Windows with the sqlite driver is nontrivial at best due to Windows being terrible.

Installing Beego

The Beego developers have made a tool called bee for easier managing of Beego projects. To install it, run:

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

The bee tool will be present in $GOPATH/bin. Please make sure this folder is in your $PATH or things will not work.

Creating a Project

Navigate to a directory in your $GOPATH and run the command bee new quickstart:

The bee tool created all the scaffolding we needed for our example program. Change into that directory and run bee run. Your application will be served on port 8080.

Now let's take a look at the parts of Beego that are in use. Beego is a typical MVC style framework so there are 3 basic places you may need to edit code:

The Models are Beego's powerful database-backed models (we'll get into those in a little bit), the Views are normal Go html/templates, and the Controllers are the Go code that controls the Views based on the Models.

New Beego projects use Beego's default HTTP router, which is similar to Sinatra or Tornado. The default router is very simple. It will only route / to the MainController that was generated for you:

The main file will shadow-include the router package which will seed the Beego router with your paths and site content. The MainController will embed beego.Controller so it acquires all instance methods that a Beego controller needs. Beego's controllers offer many methods that could be used based on different HTTP verbs, but this simple example only overrides the GET verb to serve the site. The data that will be passed to the template is a map[string]interface{} as c.Data. The last line tells Beego what template to render for the page, in this case "index.tpl". If you don't set the template it will default to "controller/method_name.tpl" where method_name is the method that was called on the controller. In this example it would be "maincontroller/get.tpl"