beego 返回数据格式 json 文本 模板
1. 文字
直接输出字符串
用法:
beego.Controller.Ctx.WriteString(“输出内容”)
2. json
输出json格式
用法:
beego.Controller.Date[“Json”]=json数据
beego.Controller.ServeJSON()调用 ServeJSON 之后,会设置 content-type 为 application/json,然后同时把数据进行 JSON 序列化输出
3. example
// Beego project main.go
package main
import (
"fmt"
"github.com/astaxie/beego"
"github.com/astaxie/beego/orm"
_ "github.com/go-sql-driver/mysql"
)
// define sql models struct
type Software struct {
ID int64 `orm:pk;auto`
ProductSN string `orm:size(200)`
ProductName string `orm:size(200)`
comment string
}
// define interface
type ResponseWork struct {
beego.Controller
}
type ResponseJson struct {
beego.Controller
}
// Get retuen ResponseWork
func (w *ResponseWork) Get() {
w.Ctx.WriteString("Rain: hello world 。。。")
}
// Get retuen ResponseJson
func (j *ResponseJson) Get() {
productName := j.GetString("product_name")
softwareID, sErr := j.GetInt("id")
offset, oErr := j.GetInt("offset")
page, pErr := j.GetInt("page")
if sErr == nil {
softwareID = 0
}
if oErr == nil {
offset = 1
}
if pErr == nil {
page = 1
}
// 根据条件查询software数据
_, softwareList, err := ListTceSoftware(productName, softwareID, page, offset)
if err != nil {
return
}
// 格式化为json数据并返回
j.Data["json"] = &softwareList
j.ServeJSON()
}
func init() {
orm.RegisterDriver("mysql", orm.DRMySQL)
// register mysql by : user passwork ip port database
orm.RegisterDataBase("default", "mysql", "user:password@tcp(ip:port)/database?charset=utf8")
orm.RegisterModel(new(Software))
}
func main() {
fmt.Println("Hello Beego")
beego.Router("/workd", &ResponseWork{})
beego.Router("/json", &ResponseJson{})
beego.Run()
}
// ListTceSoftware return softwares information
func ListTceSoftware(productName string, softwareID int, offset int, page int) (num int64, softwares []Software, err error) {
o := orm.NewOrm()
qt := o.QueryTable("tce_software")
// build query condtion
cond := orm.NewCondition()
if productName != "" {
cond = cond.And("ProductName", productName)
}
if softwareID != 0 {
cond = cond.And("ID", softwareID)
}
if page < 1 {
page = 1
}
if offset < 0 {
offset, _ = beego.AppConfig.Int("pageoffset")
}
start := (page - 1) * offset
var softwareList []Software
num, err = qt.SetCond(cond).OrderBy("-id").Limit(offset, start).All(&softwareList)
return num, softwareList, err
}