[TOC]
# 控制器介紹
>> 提示:在v1.6中,此文檔所涉及的API有重大變更,`this.serveJson()` 更改為 `this.ServeJSON()`,`this.TplNames` 更改為 `this.TplName`。
基于 beego 的 Controller 設計,只需要匿名組合 `beego.Controller` 就可以了,如下所示:
type xxxController struct {
beego.Controller
}
`beego.Controller` 實現了接口 `beego.ControllerInterface`,`beego.ControllerInterface` 定義了如下函數:
- Init(ct *context.Context, childName string, app interface{})
這個函數主要初始化了 Context、相應的 Controller 名稱,模板名,初始化模板參數的容器 Data,app即為當前執行的Controller的reflecttype,這個app可以用來執行子類的方法。
- Prepare()
這個函數主要是為了用戶擴展用的,這個函數會在下面定義的這些 Method 方法之前執行,用戶可以重寫這個函數實現類似用戶驗證之類。
- Get()
如果用戶請求的 HTTP Method 是 GET,那么就執行該函數,默認是 403,用戶繼承的子 struct 中可以實現了該方法以處理 Get 請求。
- Post()
如果用戶請求的 HTTP Method 是 POST,那么就執行該函數,默認是 403,用戶繼承的子 struct 中可以實現了該方法以處理 Post 請求。
- Delete()
如果用戶請求的 HTTP Method 是 DELETE,那么就執行該函數,默認是 403,用戶繼承的子 struct 中可以實現了該方法以處理 Delete 請求。
- Put()
如果用戶請求的 HTTP Method 是 PUT,那么就執行該函數,默認是 403,用戶繼承的子 struct 中可以實現了該方法以處理 Put 請求.
- Head()
如果用戶請求的 HTTP Method 是 HEAD,那么就執行該函數,默認是 403,用戶繼承的子 struct 中可以實現了該方法以處理 Head 請求。
- Patch()
如果用戶請求的 HTTP Method 是 PATCH,那么就執行該函數,默認是 403,用戶繼承的子 struct 中可以實現了該方法以處理 Patch 請求.
- Options()
如果用戶請求的HTTP Method是OPTIONS,那么就執行該函數,默認是 403,用戶繼承的子 struct 中可以實現了該方法以處理 Options 請求。
- Finish()
這個函數實在執行完相應的 HTTP Method 方法之后執行的,默認是空,用戶可以在子 struct 中重寫這個函數,執行例如數據庫關閉,清理數據之類的工作。
- Render() error
這個函數主要用來實現渲染模板,如果 beego.AutoRender 為 true 的情況下才會執行。
所以通過子 struct 的方法重寫,用戶就可以實現自己的邏輯,接下來我們看一個實際的例子:
```
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")
}
```
從上面的例子可以看出來,通過重寫方法可以實現對應 method 的邏輯,實現 RESTful 結構的邏輯處理。
下面我們再來看一種比較流行的架構,首先實現一個自己的基類 baseController,實現一些初始化的方法,然后其他所有的邏輯繼承自該基類:
```
type NestPreparer interface {
NestPrepare()
}
// baseRouter implemented global settings for all other routers.
type baseRouter struct {
beego.Controller
i18n.Locale
user models.User
isLogin bool
}
// Prepare implemented Prepare method for baseRouter.
func (this *baseRouter) 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 函數中那個 app 的應用,判斷當前運行的 Controller 是否是 NestPreparer 實現,如果是的話調用子類的方法,下面我們來看一下 NestPreparer 的實現:
```
type BaseAdminRouter struct {
baseRouter
}
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"
}
```
這樣我們的執行器執行的邏輯是這樣的,首先執行 Prepare,這個就是 Go 語言中 struct 中尋找方法的順序,依次往父類尋找。執行 `BaseAdminRouter` 時,查找他是否有 `Prepare` 方法,沒有就尋找 `baseRouter`,找到了,那么就執行邏輯,然后在 `baseRouter` 里面的 `this.AppController` 即為當前執行的控制器 `BaseAdminRouter`,因為會執行 `BaseAdminRouter.NestPrepare` 方法。然后開始執行相應的 Get 方法或者 Post 方法。
## 提前終止運行
我們應用中經常會遇到這樣的情況,在 Prepare 階段進行判斷,如果用戶認證不通過,就輸出一段信息,然后直接中止進程,之后的 Post、Get 之類的不再執行,那么如何終止呢?可以使用 `StopRun` 來終止執行邏輯,可以在任意的地方執行。
```
type RController struct {
beego.Controller
}
func (this *RController) Prepare() {
this.Data["json"] = "astaxie"
this.ServeJSON()
this.StopRun()
}
```
>>> 調用 StopRun 之后,如果你還定義了 Finish 函數就不會再執行,如果需要釋放資源,那么請自己在調用 StopRun 之前手工調用 Finish 函數。
## 在表單中使用 PUT 方法
首先要說明, 在 XHTML 1.x 標準中, 表單只支持 GET 或者 POST 方法. 雖然說根據標準, 你不應該將表單提交到 PUT 方法, 但是如果你真想的話, 也很容易, 通常可以這么做:
首先表單本身還是使用 POST 方法提交, 但是可以在表單中添加一個隱藏字段:
```
<form method="post" ...>
<input type="hidden" name="_method" value="put" />
```
接著在 Beego 中添加一個過濾器來判斷是否將請求當做 PUT 來解析:
```go
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)
```
- 寫在前面的話
- 第0章 beego 簡介
- 0.1 為beego貢獻
- 0.2 發布版本
- 0.3 升級指南
- 第1章 安裝升級
- 1.1 bee工具的使用
- 第2章 快速入門
- 2.1 新建項目
- 2.2 路由設置
- 2.3 Controller運行機制
- 2.4 Model邏輯
- 2.5 View編寫
- 2.6 靜態文件處理
- 第3章 beego的MVC架構
- 3.1 Model設計
- 3.1.1 概述
- 3.1.2 ORM使用
- 3.1.3 CRUD操作
- 3.1.4 高級查詢
- 3.1.5 原生SQL查詢
- 3.1.6 構造查詢
- 3.1.7 事物處理
- 3.1.8 模型定義
- 3.1.9 命令模式
- 3.1.10 測試用例
- 3.1.11 自定義字段
- 3.1.12 FAQ
- 3.2 View設計
- 3.2.1 模板語法指南
- 3.2.2 模板處理
- 3.2.3 模板函數
- 3.2.4 靜態文件處理
- 3.2.5 模板分頁處理
- 3.3 Controller設計
- 3.3.1 參數配置
- 3.3.2 路由設置
- 3.3.3 控制器函數
- 3.3.4 XSRF過濾
- 3.3.5 請求數據處理
- 3.3.6 session 控制
- 3.3.7 過濾器
- 3.3.8 flash 數據
- 3.3.9 URL構建
- 3.3.10 多種格式數據輸出
- 3.3.11 表單數據驗證
- 3.3.12 錯誤處理
- 3.3.13 日志處理
- 第4章 beego的模塊設計
- 4.1 session 模塊
- 4.2 grace 模塊
- 4.3 cache 模塊
- 4.4 logs 模塊
- 4.5 httplib 模塊
- 4.6 context 模塊
- 4.7 toolbox 模塊
- 4.8 config 模塊
- 4.9 i18n 模塊
- 第5章 beego高級編程
- 5.1 進程內監控
- 5.2 API自動化文檔
- 第6章 應用部署
- 6.1 獨立部署
- 6.2 Supervisor部署
- 6.3 Nginx 部署
- 6.4 Apache 部署
- 第7章 第三方庫
- 第8章 應用例子
- 8.1 在線聊天室
- 8.2 短域名服務
- 8.3 Todo列表
- 第9章 FAQ