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體傳參


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM