How to do it…

  1. Move to $GOPATH/src/my-first-beego-project/controllers and create firstcontroller.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["json"] = employees
this.ServeJSON()
}
  1. Move to $GOPATH/src/my-first-beego-project/routers and edit router.go to add GET mapping /employees, which will be handled by the GetEmployees handler defined in FirstController, as follows: 
package routers
import
(
"my-first-beego-project/controllers"
"github.com/astaxie/beego"
)
func init()
{
beego.Router("/", &controllers.MainController{})
beego.Router("/employees", &controllers.FirstController{},
"get:GetEmployees")
}
  1. Run the project using the following command:
$ bee run
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.4.181