beego 结构体构造及json转化
已有的beego项目实现一个查询接口,顺便记录一下常用的技术点
package controllersApi import ( "encoding/json" "fmt" "myproject/common" "myproject/models" "reflect" "github.com/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("http://127.0.0.1:1111/redis-xdb-plus/redisClusterInfo?clusterName=%v", record.ClusterName), }) } var details []*Detail data = &Data{ Result: "FAIL", 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体传参