How to do it…

  1. Move to $GOPATH/src/my-first-beego-project/controllers and create errorcontroller.go, where we will define handlers to handle 404 and 500 HTTP errors as well as the handler to handle any generic error in an application, as follows:
package controllers
import "github.com/astaxie/beego"
type ErrorController struct
{
beego.Controller
}
func (c *ErrorController) Error404()
{
c.Data["content"] = "Page Not Found"
c.TplName = "404.tpl"
}
func (c *ErrorController) Error500()
{
c.Data["content"] = "Internal Server Error"
c.TplName = "500.tpl"
}
func (c *ErrorController) ErrorGeneric()
{
c.Data["content"] = "Some Error Occurred"
c.TplName = "genericerror.tpl"
}
  1. Move to $GOPATH/src/my-first-beego-project/controllers and edit firstcontroller.go to add the GetEmployee handler, which will get the ID from an HTTP request parameter, fetch the employee details from the static employee array, and return it as a response or throw the generic error if the requested ID does not exist, 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) GetEmployee()
{
var id int
this.Ctx.Input.Bind(&id, "id")
var isEmployeeExist bool
var emps []Employee
for _, employee := range employees
{
if employee.Id == id
{
emps = append(emps, Employee{Id: employee.Id,
FirstName: employee.FirstName, LastName:
employee.LastName})
isEmployeeExist = true
break
}
}
if !isEmployeeExist
{
this.Abort("Generic")
}
else
{
this.Data["employees"] = emps
this.TplName = "dashboard.tpl"
}
}
  1. Move to $GOPATH/src/my-first-beego-project/views and create genericerror.tpl with the following content:
<!DOCTYPE html>
<html>
<body>
{{.content}}
</body>
</html>
  1. Run the program 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.20.224.107