name: Controller funcs

sort: 3

Introduction to controller

Note: From version 1.6: this.ServeJson() has been changed to this.ServeJSON() and this.TplNames has been changed to this.TplName

Beego’s controller needs to be embeded as beego.Controller:

  1. type xxxController struct {
  2. beego.Controller
  3. }

beego.Controller implements interface beego.ControllerInterface. beego.ControllerInterface defines these functions:

  • Init(ct *context.Context, controllerName, actionName string, app interface{})

    This function will initialize Context, Controller name, template name, template variable container Data. app is the executing Controller’s reflecttype. This can be used to execute the subclass’s methods.

  • Prepare()

    This function is used for extension and will execute before the methods below. It can be overwritten to implement functions such as user validation.

  • Get()

    This method will be executed if the HTTP request method is GET. It returns 403 by default. This can be used to handle GET requests by overwriting them in the struct of subclass.

  • Post()

    This method will be executed if the HTTP request method is POST. It returns 403 by default. This can be used to handle POST requests by overwriting them in the struct of subclass.

  • Delete()

    This method will be executed if the HTTP request method is DELETE. It returns 403 by default. This can be used to handle DELETE requests by overwriting them in the struct of subclass.

  • Put()

    This method will be executed if the HTTP request method is PUT. It returns 403 by default. This can be used to handle PUT requests by overwriting them in the struct of subclass.

  • Head()

    This method will be executed if the HTTP request method is HEAD. It return 403 by default. This can be used to handle HEAD requests by overwriting them in the struct of subclass.

  • Patch()

    This method will be executed if the HTTP request method is PATCH. It returns 403 by default. This can be used to handle PATCH requests by overwriting them in the struct of subclass.

  • Options()

    This method will be executed if the HTTP request method is OPTIONS. It returns 403 by default. This can be used to handle OPTIONS requests by overwriting them in the struct of subclass.

  • Finish()

    This method will be executed after finishing the related HTTP method. It is empty by default. This can be implemented by overwriting it in the struct of subclass. It is used for database closing, data cleaning and so on.

  • Render() error

    This method is used to render templates. It is only executed if beego.AutoRender is set to true.

Custom logica can be implemented by overwriting functions in struct. For example:

  1. type AddController struct {
  2. beego.Controller
  3. }
  4. func (this *AddController) Prepare() {
  5. }
  6. func (this *AddController) Get() {
  7. this.Data["content"] = "value"
  8. this.Layout = "admin/layout.html"
  9. this.TplName = "admin/add.tpl"
  10. }
  11. func (this *AddController) Post() {
  12. pkgname := this.GetString("pkgname")
  13. content := this.GetString("content")
  14. pk := models.GetCruPkg(pkgname)
  15. if pk.Id == 0 {
  16. var pp models.PkgEntity
  17. pp.Pid = 0
  18. pp.Pathname = pkgname
  19. pp.Intro = pkgname
  20. models.InsertPkg(pp)
  21. pk = models.GetCruPkg(pkgname)
  22. }
  23. var at models.Article
  24. at.Pkgid = pk.Id
  25. at.Content = content
  26. models.InsertArticle(at)
  27. this.Ctx.Redirect(302, "/admin/index")
  28. }

In the example above a RESTful structure has been implemented by overwriting functions.

The following example implements a baseController and other initialization methods that will be inherited by other controllers:

  1. type NestPreparer interface {
  2. NestPrepare()
  3. }
  4. // baseRouter implements global settings for all other routers.
  5. type baseRouter struct {
  6. beego.Controller
  7. i18n.Locale
  8. user models.User
  9. isLogin bool
  10. }
  11. // Prepare implements Prepare method for baseRouter.
  12. func (this *baseRouter) Prepare() {
  13. // page start time
  14. this.Data["PageStartTime"] = time.Now()
  15. // Setting properties.
  16. this.Data["AppDescription"] = utils.AppDescription
  17. this.Data["AppKeywords"] = utils.AppKeywords
  18. this.Data["AppName"] = utils.AppName
  19. this.Data["AppVer"] = utils.AppVer
  20. this.Data["AppUrl"] = utils.AppUrl
  21. this.Data["AppLogo"] = utils.AppLogo
  22. this.Data["AvatarURL"] = utils.AvatarURL
  23. this.Data["IsProMode"] = utils.IsProMode
  24. if app, ok := this.AppController.(NestPreparer); ok {
  25. app.NestPrepare()
  26. }
  27. }

The above example defines a base class and initializes some variables. It will test if the executing Controller is an implementation of NestPreparer. If it is it calls the method of subclass.

The example below shows an implementation of NestPreparer:

  1. type BaseAdminRouter struct {
  2. baseRouter
  3. }
  4. func (this *BaseAdminRouter) NestPrepare() {
  5. if this.CheckActiveRedirect() {
  6. return
  7. }
  8. // if user isn't admin, then logout user
  9. if !this.user.IsAdmin {
  10. models.LogoutUser(&this.Controller)
  11. // write flash message
  12. this.FlashWrite("NotPermit", "true")
  13. this.Redirect("/login", 302)
  14. return
  15. }
  16. // current in admin page
  17. this.Data["IsAdmin"] = true
  18. if app, ok := this.AppController.(ModelPreparer); ok {
  19. app.ModelPrepare()
  20. return
  21. }
  22. }
  23. func (this *BaseAdminRouter) Get(){
  24. this.TplName = "Get.tpl"
  25. }
  26. func (this *BaseAdminRouter) Post(){
  27. this.TplName = "Post.tpl"
  28. }

The above example first executes Prepare. Go will search for methods in the struct by looking in the parent classes. BaseAdminRouter will execute and checks whether there is a Prepare method. If not it keeps searching baseRouter. If there is it will execute the logic. this.AppController in baseRouter is the currently executing Controller BaseAdminRouter. Next, it will execute BaseAdminRouter.NestPrepare method. Finally, it will start executing the related GET or POST method.

Stop controller executing immediately

To stop the execution logic of a request and return the response immediately use StopRun(). For example, when a user authentication fails in Prepare method a response will be returned immediately.

  1. type RController struct {
  2. beego.Controller
  3. }
  4. func (this *RController) Prepare() {
  5. this.Data["json"] = map[string]interface{}{"name": "astaxie"}
  6. this.ServeJSON()
  7. this.StopRun()
  8. }

If you call StopRun the Finish method won’t be run. To free resources call Finish manually before calling StopRun.

Using PUT method in HTTP form

Since XHTML 1.x forms only support GET and POST these are the only allowed values for the “method” attribute. Optionally, this can be extended as follows:

Add a hidden input in the post form:

  1. <form method="post" ...>
  2. <input type="hidden" name="_method" value="put" />

Then add a filter in Beego to check if the requests should be treated as a put request:

  1. var FilterMethod = func(ctx *context.Context) {
  2. if ctx.Input.Query("_method")!="" && ctx.Input.IsPost(){
  3. ctx.Request.Method = ctx.Input.Query("_method")
  4. }
  5. }
  6. beego.InsertFilter("*", beego.BeforeRouter, FilterMethod)