beego 结构体构造及json转化

摘要:
ClusterName=%v“,record.ClusterName),})}vardetails[]*Detaildata=&Data{Result:“FAIL”,Detail:append,}}info=&info{Code:“SUCCESS”,Msg:“SUCCESS”,Data:*Data,}c。数据[“json”]=infoc。ServeJSON()return}返回数据示例{“code”:“SUCCESS”,“msg”:“SUCCESS”,“data”:{“result”:”FAIL“,“de tail”:[{“num”:2,“desc”:“pending approval form”,“items”:[{“title”:“approval表单名称1”,“url”:“xx”},{”title“approvalform名称2”,“url”:“xxx”}]}]}1。BEEGOController将工作函数绑定到控制器,然后通过路由器中的控制器条目调用该函数。2.结构通过指针初始化结构变量。修改结构时,将取消引用结构。映射通过BEEGOController的ServerJson方法转换为json格式。3.访问BEEGOORM层,格式化结果集结果集applicationRes的结构是[]模型。ClusterInfo遍历上述数组,并通过追加将其转换为类型为[]*Item的结构实例。4.支持客户端通过body传递参数

已有的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体传参

免责声明:文章转载自《beego 结构体构造及json转化》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇SpringMVC拦截器详解Winform progress bar with loading style下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

h5页面下拉到底部加载下一页数据

//页面滚到底部异步加载下一页数据 $(window).scroll(function () { //已经滚动到上面的页面高度 var scrollTop = parseFloat($(this).scrollTop()), //页面高度 scrollHeight =$(documen...

C# 与 SQLite的操作

1、通过Add References引用SQLite ADO .NET安装目录的bin目录下的System.Data.SQLite.DLL。 2、创建数据库文件:因为始终是个0字节文件,应该利用IO也可以(?!)。 System.Data.SQLite.SQLiteConnection.CreateFile(datasource);3、连接数据库 Syst...

15、高可用 PXC(percona xtradb cluster) 搭建

安装环境: 集群名 pxc_lk 节点1: 192.168.1.20 节点2: 192.168.1.21 节点3: 192.168.1.22 所有节点安装 wgethttp://www.percona.com/redir/downloads/XtraBackup/LATEST/binary/redhat/6/x86_64/percona...

vue 中使用 axios 封装及使用

一, 配置BaseUrl /** * { * dev: '开发环境配置信息', * test: '测试环境配置信息', * prod: '线上环境配置信息' * } */ function conf (base = {}) { if (process.env.NODE_ENV === 'production' || proces...

实践(1):简单的文件上传

文件上传 html、修改 <div class="template-upload"> <span>模版样式:</span> <button type="button" id="btn">选择模板</button> <input type="file" accept=".pptx,.ppt...

Axios 各种请求方式传递参数格式

为方便起见,为所有支持的请求方法提供了别名 在使用别名方法时, url、method、data 这些属性都不必在配置中指定 axios.request(config) axios.get(url[, config]) axios.delete(url[, config]) axios.head(url[, config]) axios.post(ur...