定义Result
result.go
package models
const (
CodeSuccess = "0000"
CodeFailed = "0001"
)
type Result struct {
Code string `json:"code"`
Msg string `json:"msg"`
Data interface{} `json:"data"`
}
func Success() *Result {
return &Result{Code: CodeSuccess, Msg: "SUCCESS"}
}
func SuccessData(data interface{}) *Result {
return &Result{Code: CodeSuccess, Msg: "SUCCESS", Data: &data}
}
func Fail() *Result {
return &Result{Code: CodeFailed, Msg: "FAILED"}
}
func FailMsg(msg string) *Result {
return &Result{Code: CodeFailed, Msg: msg}
}
使用
region.go
package controllers
import (
"beego_demo/lib/mysql"
"beego_demo/models"
"encoding/json"
"github.com/astaxie/beego"
"github.com/astaxie/beego/logs"
)
type RegionController struct {
beego.Controller
}
func (c *RegionController) List() {
logs.Info("这是测试日志: %s", "test")
var listRegion []models.Region
listRegion, _ = models.ListRegion(c.GetString("parentCode"))
c.Data["json"] = models.SuccessData(&listRegion)
c.ServeJSON()
}
func (c *RegionController) Create() {
var region models.Region
_ = json.Unmarshal(c.Ctx.Input.RequestBody, ®ion)
createRegion, err := mysql.Create(®ion)
println("执行结果: %d", createRegion)
if err != nil {
c.Data["json"] = models.FailMsg("System error...")
} else {
c.Data["json"] = models.Success()
}
c.ServeJSON()
}