Creating your first controller and router
One of the main components of a web application is the controller, which acts as a coordinator between the view and the model and handles the user's requests, which could be a button click, or a menu selection, or HTTP GET
and POST
requests. In this recipe, we will learn how we can create a controller in Beego.
How to do it…
- Move to
$GOPATH/src/my-first-beego-project/controllers
and createfirstcontroller.go
, as follows:
package controllers import "github.com/astaxie/beego" type FirstController struct { beego.Controller } type Employee struct { Id int `json:"id"` FirstName string `json:"firstName"` LastName string `json:"lastName"` } type Employees []Employee var employees []Employee func init() { employees = Employees { Employee{Id: 1, FirstName: "Foo", LastName: "Bar"}, Employee{Id: 2, FirstName: "Baz", LastName: "Qux"}, } } func (this *FirstController) GetEmployees() { this.Ctx.ResponseWriter.WriteHeader(200) this.Data...