Go Revel - Results(響應)
每個`Action`必須返回一個`revel.Result`實例,用來處理響應。它遵循了簡單的接口:
type Result interface {
Apply(req *Request, resp *Response)
}
`revel.Controller`提供了一些方法來生成`Results`響應:
1、`Render`, `RenderTemplate` - 渲染模板, 傳遞參數
2、`RenderJson`, `RenderXml` - 將一個`struct`序列化為`json`或`xml`格式
3、`RenderText` - 返回一個純文本響應
4、`Redirect` - 重定向到另一個`action`或URL
5、`RenderFile` - 返回一個文件, 一般作為一個附件下載
6、`RenderError` - 渲染`errors/500.html`模板來返回一個500狀態
7、`NotFound` - 渲染`errors/404.html`模板來返回一個404狀態
8、`Todo` - 返回一個存根響應 (500)
除此之外,開發人員還可以返回自己定義的`revel.Result`
**設置狀態碼與返回體**
每一個內建的`Result`都有默認的狀態碼與返回體,如果要手動改變,只需要簡單的覆蓋`response`中的屬性即可:
func (c App) Action() revel.Result {
c.Response.Status = http.StatusTeapot
c.Response.ContentType = "application/dishware"
return c.Render()
}
##Render(渲染器)
在一個`action`內調用(如,`Controller.Action`)。`mvc.Controller.Render`可以做如下兩件事:
1、將所有參數添加至controller的`RenderArgs`,并將它們的本地標識設置為key
2、渲染模板`views/Controller/Action.html`, 并將`RenderArgs`作為一個map傳遞
如果不成功,比如沒找到模板,它會返回一個`ErrorResult`對象。
func (c MyApp) Action() revel.Result {
myValue := calculateValue()
return c.Render(myValue)
}
上面示例將`myValue`傳遞至模板。
revel需要根據調用者的方法名來確定模板的路徑與參數,因此`c.Render()`只能在Action中調用。
##渲染 Json / Xml
程序可以通過傳遞任意Go類型來調用`RenderJson`或`RenderXml`,revel將通過`json.Marshal`或`xml.Marshal`來渲染。
如果`app.conf`中的`results.pretty=true`被定義,則將使用`MarshalIndent`進行序列化,以慘生更好的縮進供人閱讀。
##Redirect(重定向)
revel提供了一下兩種方式來進行重定向:
1、不傳遞參數來重定向至一個action
return c.Redirect(Hotels.Settings)
這種方式十分有用,它提供一定程度的類型安全與獨立路由(會自動的生成URL)
2、使用一個格式化字符串重定向
return c.Redirect("/hotels/%d/settings", hotelId)
這種形式必須傳遞參數
它會返回一個302(臨時重定向)狀態碼
##添加自定義Result
下面的示例演示如何創建一個自定義`Result`
創建如下類型:
type Html string
func (r Html) Apply(req *Request, resp *Response) {
resp.WriteHeader(http.StatusOK, "text/html")
resp.Out.Write([]byte(r))
}
并在action中使用:
func (c *App) Action() revel.Result {
return Html("Hello World")
}
##狀態碼
沒一個`Result`都具有默認的狀態碼,可以很方便的更改它:
func (c *App) CreateEntity() revel.Result {
c.Response.Status = 201
return c.Render()
}
浙公網安備 33010602011771號