golang - 利用 stuct 方法处理 json 数据方法

9 篇文章 0 订阅

目的

1. 利用 golang 调用 ceph 存储     
2. 获取 ceph json 数据并进行处理  
3. 利用 struct  结构对 json 数据进行处理    

参考

golang ceph 连接方法

struct 处理

优点

  1. 结构清晰
  2. 代码维护方便

缺点

  1. 需要预定义 struct 结构
  2. 只能够对已知的 json 结构创建对应的 struct
  3. 如果每次 json 输出的 key 不一样就十分不方便 (gjsno 包可以利用 # 的方法自动匹配)

语法参考

models/cephstruct.go 定义了整个 json 输出的结构

package models

type CephMonStruct struct {

        // command:  ceph mon_status

        Name          string `json:"name"`
        Rank          int    `json:"rank"`
        State         string `json:"state"`
        ElectionEpoch int    `json:"election_epoch"`
        Quorum        []int  `json:"quorum"`
        Features      struct {
                RequiredCon string   `json:"required_con"`
                RequiredMon []string `json:"required_mon"`
                QuorumCon   string   `json:"quorum_con"`
                QuorumMon   []string `json:"quorum_mon"`
        } `json:"features"`
        OutsideQuorum   []interface{} `json:"outside_quorum"`
        ExtraProbePeers []interface{} `json:"extra_probe_peers"`
        SyncProvider    []interface{} `json:"sync_provider"`
        Monmap          struct {
                Epoch    int    `json:"epoch"`
                Fsid     string `json:"fsid"`
                Modified string `json:"modified"`
                Created  string `json:"created"`
                Features struct {
                        Persistent []string      `json:"persistent"`
                        Optional   []interface{} `json:"optional"`
                } `json:"features"`
                Mons []struct {
                        Rank       int    `json:"rank"`
                        Name       string `json:"name"`
                        Addr       string `json:"addr"`
                        PublicAddr string `json:"public_addr"`
                } `json:"mons"`
        } `json:"monmap"`
        FeatureMap struct {
                Mon struct {
                        Group struct {
                                Features string `json:"features"`
                                Release  string `json:"release"`
                                Num      int    `json:"num"`
                        } `json:"group"`
                } `json:"mon"`
                Osd struct {
                        Group struct {
                                Features string `json:"features"`
                                Release  string `json:"release"`
                                Num      int    `json:"num"`
                        } `json:"group"`
                } `json:"osd"`
                Client struct {
                        Group struct {
                                Features string `json:"features"`
                                Release  string `json:"release"`
                                Num      int    `json:"num"`
                        } `json:"group"`
                } `json:"client"`
        } `json:"feature_map"`
}

现在参考 client/cephmon.go 获取 quorum 中的 []slice 方法

package client

import (
    "fmt"
    "os"
    "github.com/ceph/go-ceph/rados"
    "encoding/json"
    "models"
)

func ConnCephStruct (param string) (resp []byte, err error ) {

    conn, err := rados.NewConn()
    if err != nil {
        resp = []byte("1")
        fmt.Printf("ConnCephStruct() can not get %s info, %s", param, err )
        return
    }

    err = conn.ReadDefaultConfigFile()
    if err != nil{
        resp = []byte("1")
        fmt.Printf("ConnCephStruct() can not get %s info, %s", param, err )
        return
    }

    err = conn.Connect()
    if err != nil{
        resp = []byte("1")
        fmt.Printf("ConnCephStruct() can not get %s info, %s", param, err )
        return
    }

    resp, _, err = conn.MonCommand([]byte(`{"prefix":"` + param + `", "format":"json-pretty"}`))
    if err != nil {
        resp = []byte("1")
        fmt.Printf("ConnCephStruct() can not get %s info, %s", param, err )
        return
    }

    if err != nil {
        resp = []byte("1")
        fmt.Printf("ConnCephStruct() can not get %s info, %s", param, err )
        return
    }

    conn.Shutdown()

    return
}



func GetCephMaster()( cephQuorams []int, err error  ){

    mon_status := "mon_status"
    cephInfo, err := ConnCephStruct(mon_status)

    if err != nil {
        fmt.Printf("GetMonStatus() can not get 'mon_status' info  %s " , err)
        os.Exit(1)
    }

    if len(cephInfo) == 1 {
        fmt.Printf("GetMonStatus() can not get 'mon_status' ")
        os.Exit(1)
    }

    var cephMonDetail  models.CephMonStruct            <- 套用了 struct 结构
    _ = json.Unmarshal( cephInfo, &cephMonDetail)

    cephQuorams = cephMonDetail.Quorum                 <- 获取 struct 中 Quorum 字段数据
    return

}

参考输出结果

go run main.go
[]int
[0 1 2]

参考获取 stuct 的其他方法

cephMonDetail.Name           "ns-storage-020100"
cephMonDetail.Monmap.Fsid    "8085cc2f-d5ec-48d2-b614-fxxxxxxxxxxxxx"

假如要获取 mons 中下面所有 name 的方法

"mons": [
        {
            "rank": 0,
            "name": "ns-storage-020100",
            "addr": "xx.xxx.xx.100:6789/0",
            "public_addr": "xx.xxx.xx.100:6789/0"
        },
        {
            "rank": 1,
            "name": "ns-storage-020101",
            "addr": "xx.xxx.xx.101:6789/0",
            "public_addr": "xx.xxx.xx.101:6789/0"
        },
        {
            "rank": 2,
            "name": "ns-storage-020102",
            "addr": "xx.xxx.xx.102:6789/0",
            "public_addr": "xx.xxx.xx.102:6789/0"
        }
	]

参考语法

monsInfo := cephMonDetail.Monmap.Mons
hosts make([]string,0)
for _, i := range monsInfo {
	hosts := append(hosts, i.Name)         <- 判断,字符匹配等功能都可以通过 golang 实现(略)
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Terry_Tsang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值