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. web.Controller
  3. }

web.Controller implements interface web.ControllerInterface. web.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.

  • Trace() error

    This method will be executed if the HTTP request method is TRACE. It returns 403 by default. This can be used to handle TRACE 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 web.AutoRender is set to true.

  • Mapping(method string, fn func())

    Register a method. Generally, the method is valid HTTP method name.

  • HandlerFunc(fnname string) bool

    Execute the method that register by Mapping method. It return false when fnname not found.

  • RenderBytes() ([]byte, error)

    Render the template and output the result as []byte. This method doesn’t check EnableRender option, and it doesn’t output the result to response.

  • RenderString() (string, error)

    Similar with RenderBytes()

  • Redirect(url string, code int)

    Redirect the request to url

  • SetData(data interface{})

    Store data to controller. Usually you won’t use this method.

  • Abort(code string)

    Breaking current method with the code. errors

  • CustomAbort(status int, body string)

    Breaking current method with the code. errors

  • StopRun()

    Trigger panic.

  • ServeXXX(encoding …bool) error

    Return response with the specific format. Supporting JSON, JSONP, XML, YAML. Output

  • ServeFormatted(encoding …bool) error

    Return response with specific format passed from client’s Accept option. Output

  • Input() (url.Values, error)

    Return all parameters.

  • ParseForm(obj interface{}) error

    Deserialize form to obj.

  • GetXXX(key string, def…) XXX, err

    Read value from parameters. If the def not empty, return def when key not found or error. XXX coule be basic types, string or File.

  • SaveToFile(fromfile, tofile string) error

    Save the uploading file to file system. fromfile is uploading file name.

  • SetSession(name interface{}, value interface{}) error

    Put some value into session.

  • GetSession(name interface{}) interface{}

    Read value from session.

  • DelSession(name interface{}) error

    Delete the value from session.

  • SessionRegenerateID() error

    Re-generate session id.

  • DestroySession() error

    Destroy session.

  • IsAjax() bool

    Check whether is ajax request.

  • GetSecureCookie(Secret, key string) (string, bool)

    Read value from cookie.

  • SetSecureCookie(Secret, name, value string, others …interface{})

    Put key-value pair into cookie.

  • XSRFToken() string

    Create CSRF token.

  • CheckXSRFCookie() bool

    Check CSRF token

Custom logic

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

  1. type AddController struct {
  2. web.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. web.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. web.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.