beego controller Introduction

Controller Introduction

Tip: In the v1.6 , API this document involved a major change, this.ServeJson() change  this.ServeJSON(), this.TplNames change  this.TplName.

Controller Design Based beego, just anonymous compositions  beego.Controller can, as shown below:

type xxxController struct { beego.Controller }

beego.Controller Implements the interface  beego.ControllerInterface, beego.ControllerInterface it defines the following functions:

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

    The main function initializes the Context, corresponding Controller name, template name, container Data initialization parameter template , app is the Controller of reflecttype currently executing, this app can be used to perform the method of the subclass .

  • Prepare()

    This function is mainly used for user extensions, which defines the function in the following performed before Method methods , the user can override this function to achieve a similar user authentication or the like.

  • Get()

    If the user requests are HTTP Method GET, then the function is executed, the default is 405, the sub-struct user inherits the method can be implemented to handle Get request.

  • Post()

    If the user requests the HTTP Method is POST, then the function is executed, the default is 405, the sub-struct user inherits the method can be implemented to handle Post request.

  • Delete()

    If the user requests the HTTP Method is the DELETE, then the function is executed, the default is 405, the sub-struct user inherits the method can be implemented to handle the Delete request.

  • Put()

    If the user requests are HTTP Method PUT, then the function is executed, the default is 405, the sub-struct user inherits the method can be implemented to handle Put request.

  • Head()

    If the user requests are HTTP Method HEAD, then the function is executed, the default is 405, the sub-struct user inherits the method can be implemented to handle Head request.

  • Patch()

    If the user requests the PATCH HTTP Method is, then the function is executed, the default is 405, the sub-struct user inherits the method can be implemented to handle requests Patch.

  • Options()

    If the user requests are HTTP Method OPTIONS, then the function is executed, the default is 405, the sub-struct user inherits the method can be implemented to handle requests Options.

  • Finish()

    This function is performed in End corresponding HTTP performed after the method of Method empty by default, the user can override this function in the struct child, such as database performs closed, the work of cleaning up the data class.

  • Render() error

    This function is mainly used to implement template rendering , it will be performed in the case if beego.AutoRender is true.

Therefore, the method by rewriting sub-struct, users can implement their own logic, let's look at a practical example:

type AddController struct { beego.Controller } func (this *AddController) Prepare() { } func (this *AddController) Get() { this.Data["content"] = "value" this.Layout = "admin/layout.html" this.TplName = "admin/add.tpl" } func (this *AddController) Post() { pkgname := this.GetString("pkgname") content := this.GetString("content") pk := models.GetCruPkg(pkgname) if pk.Id == 0 { var pp models.PkgEntity pp.Pid = 0 pp.Pathname = pkgname pp.Intro = pkgname models.InsertPkg(pp) pk = models.GetCruPkg(pkgname) } var at models.Article at.Pkgid = pk.Id at.Content = content models.InsertArticle(at) this.Ctx.Redirect(302, "/admin/index") }

Can be seen from the above examples, may be implemented by a method corresponding to the logical overwriting method, the processing logic implemented RESTful structure.

Here we look at a more popular architecture, first of all to achieve its own base class baseController, implement some method to initialize, and then all the other logic inherited from the base class:

type NestPreparer interface { NestPrepare() } // baseRouter implemented global settings for all other routers. type baseController struct { beego.Controller i18n.Locale user models.User isLogin bool } // Prepare implemented Prepare method for baseRouter. func (this *baseController) Prepare() { // page start time this.Data["PageStartTime"] = time.Now() // Setting properties. this.Data["AppDescription"] = utils.AppDescription this.Data["AppKeywords"] = utils.AppKeywords this.Data["AppName"] = utils.AppName this.Data["AppVer"] = utils.AppVer this.Data["AppUrl"] = utils.AppUrl this.Data["AppLogo"] = utils.AppLogo this.Data["AvatarURL"] = utils.AvatarURL this.Data["IsProMode"] = utils.IsProMode if app, ok := this.AppController.(NestPreparer); ok { app.NestPrepare() } }
/*
分析一线init方法的实现过程
Methods c.AppController on behalf of the interface, you can call the subclass
this.AppController.(NestPreparer)
Determining whether the current operation is the Controller NestPreparer achieve
 
// Init generates default values of controller operations.
func (c *Controller) Init(ctx *context.Context, controllerName, actionName string, app interface{}) {
	c.Layout = ""
	c.TplName = ""
	c.controllerName = controllerName
	c.actionName = actionName
	c.Ctx = ctx
	c.TplExt = "tpl"
	c.AppController = app
	c.EnableRender = true
	c.EnableXSRF = true
	c.Data = ctx.Input.Data()
	c.methodMapping = make(map[string]func())
}


*/

The above definition of the base class, probably to initialize some variables, and finally there is a Init function in the application of the app is to determine whether the current operation is the Controller NestPreparer achieved, and if so for subclasses to call, let's look at NestPreparer of achieve:

type BaseAdminRouter struct { baseController } func (this *BaseAdminRouter) NestPrepare() { if this.CheckActiveRedirect() { return } // if user isn't admin, then logout user if !this.user.IsAdmin { models.LogoutUser(&this.Controller) // write flash message this.FlashWrite("NotPermit", "true") this.Redirect("/login", 302) return } // current in admin page this.Data["IsAdmin"] = true if app, ok := this.AppController.(ModelPreparer); ok { app.ModelPrepare() return } } func (this *BaseAdminRouter) Get(){ this.TplName = "Get.tpl" } func (this *BaseAdminRouter) Post(){ this.TplName = "Post.tpl" }

Such logic executing our execution is first executed Prepare, this is the Go language struct in order to find ways, in order to find the parent class. Execution  BaseAdminRouter time, find out if he has  Prepare a method, not to seek  baseController, to find, and then perform the logic, then  baseController inside  this.AppController that is currently executing the controller BaseAdminRouter , because the execution will  BaseAdminRouter.NestPrepare approach. Then begins executing the Get method or Post method.

Early Termination run

Our applications often encounter such a case, the judge at Prepare stage, if the user authentication fails, it prints a message and then directly killing the process, after the Post, Get the like are no longer executed, how to terminate it? Can be used  StopRun to terminate execution logic can be executed at any place.

type RController struct { beego.Controller } func (this *RController) Prepare() { this.Data["json"] = map[string]interface{}{"name": "astaxie"} this.ServeJSON() this.StopRun() }

After calling StopRun, if you define Finish function will not execute, if need to release resources, so please yourself before calling StopRun manually invoke Finish functions.

PUT method used in the form

Firstly I should say, in XHTML 1.x standard, the form only supports GET or POST method. Although according to the standard, you should not submit the form to the PUT method, but if you really want it, is also very easy, you can usually do so :

First, the form itself is submitted using the POST method, but you can add a hidden field in the form:

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

Followed by addition of a filter to determine whether the Beego as PUT request to resolve:

var FilterMethod = func(ctx *context.Context) { if ctx.BeegoInput.Query("_method")!="" && ctx.BeegoInput.IsPost(){ ctx.Request.Method = ctx.BeegoInput.Query("_method") } } beego.InsertFilter("*", beego.BeforeRouter, FilterMethod)

Guess you like

Origin www.cnblogs.com/show58/p/12368121.html