golang -上传 json 数据方法
目的
1. 利用 struct 组合数据
2. 利用 struct 上传 json 数据至 django
参考
golang - 利用 stuct 方法处理 json 数据方法
golang - 利用 gjson 处理 json 数据方法
代码结构
[root@ns-yun-020049 go]# tree src
src
├── client
│ └── cephmon.go <- 程序方法
├── main.go <- 入口
├── models
│ ├── cephstruct.go <- 获取 ceph mon 结构
│ └── uploadstruct.go <- 定义 upload json 结构
└── vendor
└── github.com
└── ceph
└── go-ceph <- 第三方包
struct 定义
根据 ceph mon_status -f json-pretty 命令返回结果定义了整个结构
[root@ns-yun-020049 src]# cat models/cephstruct.go
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"`
}
定义了即将上传成为 json 的数据结构
[root@ns-yun-020049 src]# cat models/uploadstruct.go
package models
type MonStatus struct {
IpAddr string `json:"ipaddr"`
HostName string `json:"hostname"`
}
type UploadStatus struct {
Rank int `json:"rank"`
Mons MonStatus `json:"monstat"`
}
参考 获取 ceph 数据并组合到新 struct 结构方法
[root@ns-yun-020049 src]# cat client/cephmon.go
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 GetCephMasters()( cephMonstat []models.UploadStatus, 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
err = json.Unmarshal( cephInfo, &cephMonDetail) <- ceph 命令数据存放至 cephMonDetail 结构中
cephMons := cephMonDetail.Monmap.Mons <- 只取 Mons 中的返回数据
for _, i := range cephMons {
var cephStatus models.UploadStatus <- 数据重新定义到 cephStatus 中
var monStatus models.MonStatus
cephStatus.Rank = i.Rank
monStatus.IpAddr = i.Addr
monStatus.HostName = i.Name
cephStatus.Mons = monStatus
cephMonstat = append(cephMonstat, cephStatus)
}
return
}
当前函数 cephStatus() 将会返回下面效果
[{0 {10.189.20.100:6789/0 ns-storage-020100}} {1 {10.189.20.101:6789/0 ns-storage-020101}} {2 {10.189.20.102:6789/0 ns-storage-020102}}]
上传方法
[root@ns-yun-020049 src]# cat client/curlpost.go
package client
import (
"fmt"
"net/http"
"io/ioutil"
"encoding/json"
"bytes"
)
func SendListData(s interface{}, serverUrl string) (result []byte) {
b, _ := json.Marshal(s)
body := bytes.NewBuffer([]byte(b))
res, err := http.Post(serverUrl, "application/json;charset=utf-8", body)
if err != nil {
fmt.Println("post err:", err)
return
}
result, err = ioutil.ReadAll(res.Body)
res.Body.Close()
if err != nil {
fmt.Println("post err:", err)
return
}
return
}
注意
当前上传的数据为 python list 结构, 因此定义了参数传入定义为 interface{} 类型
假如上传的数据为 python dict 结构, 需要定义参数传入定义为 map[string]interface{} 类型
定义另外一个函数即可
func SenDictdData(s map[string]interface{}, serverUrl string) (result []byte) {
主函数上传数据方法
package main
import (
"fmt"
_ "reflect"
"client"
)
func main(){
var postData interface{}
url := "http://10.199.210.114/upload/"
postData, _ = client.GetCephMasters()
postInfo := client.SendListData(postData, url)
fmt.Println(string(postInfo))
}
参考 django 获得数据如下:
<type 'list'>
[{u'rank': 0, u'monstat': {u'hostname': u'ns-storage-020100', u'ipaddr': u'10.189.20.100:6789/0'}}, {u'rank': 1, u'monstat': {u'hostname': u'ns-storage-020101', u'ipaddr': u'10.189.20.101:6789/0'}}, {u'rank': 2, u'monstat': {u'hostname': u'ns-storage-020102', u'ipaddr': u'10.189.20.102:6789/0'}}]
结果:
1. 数据类型为 python list 结构
2. 直接使用了 models/uploadstruct.go 中的 UploadStatus 结构体
3. 直接使用结构体中的 json 定义了数据
还没有评论,来说两句吧...