beego结构体构造及json转化已有的beego项⽬实现⼀个查询接⼝,顺便记录⼀下常⽤的技术点
package controllersApi
import (
"encoding/json"
"fmt"
"myproject/common"
"myproject/models"
"reflect"
"github/astaxie/beego"
)
// 获取⽤户所负责的集相关的结构体
type Item struct {
Title string `json:"title"`
Url  string `json:"url"`
}
type Detail struct {
Num  int    `json:"num"`
Desc  string  `json:"desc"`
Items []*Item `json:"items"`
}
type Data struct {
Result string    `json:"result"`
Detail []*Detail `json:"detail"`
}
type Info struct {
Code string `json:"code"`
Msg  string `json:"msg"`
Data Data  `json:"data"`
}
type Args struct {
UserName string `json:"username"`
}
type ApiDemandController struct {
beego.Controller
}
// 获取某个⽤户负责的集
func (c *ApiDemandController) QueryUserRes() {
var userName string
userName = c.GetString("username")
// 优先从get⽅法中获取参数,如果获取不到则从body体中获取
fmt.Printf("from get username [%s] [%v]", userName, reflect.TypeOf(userName))
if userName == "" {
args := Args{}
var err error
if err = json.Unmarshal(c.Ctx.Input.RequestBody, &args); err == nil {
userName = args.UserName
} else {
res := fmt.Sprintf("Fail to parse request body reason=[%v],username=[%v]", err, userName)
common.Log.Warn(res)
info := &Info{
Code: "FAIL",
Msg:  res,
}
c.Data["json"] = info
c.ServeJSON()
return
}
}
clusterInfo := models.ClusterInfo{Applicant: userName}
applicantRes, err := clusterInfo.ReadRecordsByCols([]string{"Applicant"})
var info *Info
if err != nil {
res := fmt.Sprintf("Fail to get user's resources reason=[%v],username=[%v]", err, userName)
common.Log.Warn(res)
info = &Info{
Code: "FAIL",
Msg:  res,
}
c.Data["json"] = info
c.ServeJSON()
return
}
var data *Data
num := len(applicantRes)
if num == 0 {
data = &Data{
Result: "PASS",
}
} else {
var items []*Item
for _, record := range applicantRes {
items = append(items, &Item{
Title: record.ClusterName,
Url:  fmt.Sprintf("127.0.0.1:1111/redis-xdb-plus/redisClusterInfo?clusterName=%v", record.ClusterName),            })
}
var details []*Detail
data = &Data{
Result: "FAIL",
浏览器json格式化
Detail: append(details, &Detail{
Num:  num,
Desc:  "负责的集",
Items: items,
}),
}
}
info = &Info{
Code: "SUCCESS",
Msg:  "成功",
Data: *data,
}
c.Data["json"] = info
c.ServeJSON()
return
}
返回数据⽰例
{
"code":"SUCCESS",
"msg":"成功",
"data":{
"result":"FAIL",
"detail":[
{
"num":2,
"desc":"待审批单",
"items":[
{
"title":"审批单名称1",
"url":"xx"
},
{
"title":"审批单名称2",
"url":"xx"
}
]
}
]
}
}
1、beego controller
将⼯作函数绑定到controller,然后router中通过controller⼊⼝调⽤函数
2、构造结构体
通过指针的⽅式初始化结构体变量,修改结构体的时候,对结构体解引⽤
通过beego controller的ServerJson⽅法将map转换为json格式
3、访问beego orm层,格式化结果集
结果集applicantRes 的结构体为 []models.ClusterInfo
遍历上⾯的数组通过append⽅式将其转化为[]*Item 类型的结构体实例
4、⽀持客户端通过body体传参

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。