經過beego.Controller.Ctx.WriteString()
方法能夠直接向http response body中輸出字符串javascript
beego中的函數定義以下:html
// WriteString Write string to response body. // it sends response body. func (ctx *Context) WriteString(content string) { ctx.ResponseWriter.Write([]byte(content)) }
示例:直接在response body中輸出Hello World!
java
package controllers import ( "github.com/astaxie/beego" ) type MainController struct { beego.Controller } func (c *MainController) Get() { c.Ctx.WriteString("Hello World!") }
打開http跟蹤能夠看到,在http response body中只有Hello World!
,都沒有html標籤。git
經過簡單的指定beego.Controller.TplName
模板文件,http response body將輸出模板文件對應的內容。github
示例:web
package controllers import ( "github.com/astaxie/beego" ) type MainController struct { beego.Controller } func (c *MainController) Get() { c.TplName = "hello.tpl" }
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> </head> <body> <h1>Hello World!</h1> </body> </html>
在web中大部分的內容是靜態的,只有少部分數據是動態的。爲了複用模板的代碼,須要可以把動態的數據插入到模板中,這須要特出的語法。json
beego中模板經過{{}}
包含須要被替換的字段,同時須要把要替換的內容添加到Controller的Data
中,這樣Controller執行時會自動匹配渲染模板。app
示例:函數
package controllers import ( "github.com/astaxie/beego" ) type MainController struct { beego.Controller } func (c *MainController) Get() { c.Data["Email"] = "arestrack@163.com" c.TplName = "hello.tpl" }
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> </head> <body> <h1>Hello World!</h1> Contact me: <a class="email" href="mailto:{{.Email}}">{{.Email}}</a> </body> </html>
經過把要輸出的數據放到Data["json"]
中,而後調用ServeJSON()
進行渲染,就能夠把數據進行JSON序列化輸出。jsonp
beego中ServeJSON()
函數定義以下:
// ServeJSON sends a json response with encoding charset. func (c *Controller) ServeJSON(encoding ...bool) { var ( hasIndent = true hasEncoding = false ) if BConfig.RunMode == PROD { hasIndent = false } if len(encoding) > 0 && encoding[0] { hasEncoding = true } c.Ctx.Output.JSON(c.Data["json"], hasIndent, hasEncoding) }
示例:
type JSONStruct struct { Code int Msg string } func (c *MainController) Get() { mystruct := &JSONStruct{0, "hello"} c.Data["json"] = mystruct c.ServeJSON() }
經過把要輸出的數據放到Data["xml"]
中,而後調用ServeXML()
進行渲染,就能夠把數據進行XML序列化輸出。
beego中ServeXML()
函數定義以下:
// ServeXML sends xml response. func (c *Controller) ServeXML() { hasIndent := true if BConfig.RunMode == PROD { hasIndent = false } c.Ctx.Output.XML(c.Data["xml"], hasIndent) }
示例:
type XMLStruct struct { Code int Msg string } func (c *MainController) Get() { mystruct := &XMLStruct{0, "hello"} c.Data["xml"] = mystruct c.ServeXML() }
經過把要輸出的數據放到Data["jsonp"]
中,而後調用ServeJSONP()
進行渲染,會設置content-type
爲application/javascript
,而後同時把數據進行JSON序列化,而後根據請求的callback參數設置jsonp輸出。
beego中ServeJSONP()
函數定義以下:
// ServeJSONP sends a jsonp response. func (c *Controller) ServeJSONP() { hasIndent := true if BConfig.RunMode == PROD { hasIndent = false } c.Ctx.Output.JSONP(c.Data["jsonp"], hasIndent) }
示例:
type JSONStruct struct { Code int Msg string } func (c *MainController) Get() { mystruct := &JSONStruct{0, "hello"} c.Data["jsonp"] = mystruct c.ServeJSONP() }