golang -上传 json 数据方法

曾经终败给现在 2022-03-29 11:12 314阅读 0赞

目的

  1. 1. 利用 struct 组合数据
  2. 2. 利用 struct 上传 json 数据至 django

参考

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

代码结构

  1. [root@ns-yun-020049 go]# tree src
  2. src
  3. ├── client
  4. └── cephmon.go <- 程序方法
  5. ├── main.go <- 入口
  6. ├── models
  7. ├── cephstruct.go <- 获取 ceph mon 结构
  8. └── uploadstruct.go <- 定义 upload json 结构
  9. └── vendor
  10. └── github.com
  11. └── ceph
  12. └── go-ceph <- 第三方包

struct 定义

根据 ceph mon_status -f json-pretty 命令返回结果定义了整个结构

  1. [root@ns-yun-020049 src]# cat models/cephstruct.go
  2. package models
  3. type CephMonStruct struct {
  4. // command: ceph mon_status
  5. Name string `json:"name"`
  6. Rank int `json:"rank"`
  7. State string `json:"state"`
  8. ElectionEpoch int `json:"election_epoch"`
  9. Quorum []int `json:"quorum"`
  10. Features struct {
  11. RequiredCon string `json:"required_con"`
  12. RequiredMon []string `json:"required_mon"`
  13. QuorumCon string `json:"quorum_con"`
  14. QuorumMon []string `json:"quorum_mon"`
  15. } `json:"features"`
  16. OutsideQuorum []interface{} `json:"outside_quorum"`
  17. ExtraProbePeers []interface{} `json:"extra_probe_peers"`
  18. SyncProvider []interface{} `json:"sync_provider"`
  19. Monmap struct {
  20. Epoch int `json:"epoch"`
  21. Fsid string `json:"fsid"`
  22. Modified string `json:"modified"`
  23. Created string `json:"created"`
  24. Features struct {
  25. Persistent []string `json:"persistent"`
  26. Optional []interface{} `json:"optional"`
  27. } `json:"features"`
  28. Mons []struct {
  29. Rank int `json:"rank"`
  30. Name string `json:"name"`
  31. Addr string `json:"addr"`
  32. PublicAddr string `json:"public_addr"`
  33. } `json:"mons"`
  34. } `json:"monmap"`
  35. FeatureMap struct {
  36. Mon struct {
  37. Group struct {
  38. Features string `json:"features"`
  39. Release string `json:"release"`
  40. Num int `json:"num"`
  41. } `json:"group"`
  42. } `json:"mon"`
  43. Osd struct {
  44. Group struct {
  45. Features string `json:"features"`
  46. Release string `json:"release"`
  47. Num int `json:"num"`
  48. } `json:"group"`
  49. } `json:"osd"`
  50. Client struct {
  51. Group struct {
  52. Features string `json:"features"`
  53. Release string `json:"release"`
  54. Num int `json:"num"`
  55. } `json:"group"`
  56. } `json:"client"`
  57. } `json:"feature_map"`
  58. }

定义了即将上传成为 json 的数据结构

  1. [root@ns-yun-020049 src]# cat models/uploadstruct.go
  2. package models
  3. type MonStatus struct {
  4. IpAddr string `json:"ipaddr"`
  5. HostName string `json:"hostname"`
  6. }
  7. type UploadStatus struct {
  8. Rank int `json:"rank"`
  9. Mons MonStatus `json:"monstat"`
  10. }

参考 获取 ceph 数据并组合到新 struct 结构方法

  1. [root@ns-yun-020049 src]# cat client/cephmon.go
  2. package client
  3. import (
  4. "fmt"
  5. "os"
  6. "github.com/ceph/go-ceph/rados"
  7. "encoding/json"
  8. "models"
  9. )
  10. func ConnCephStruct (param string) (resp []byte, err error ) {
  11. conn, err := rados.NewConn()
  12. if err != nil {
  13. resp = []byte("1")
  14. fmt.Printf("ConnCephStruct() can not get %s info, %s", param, err )
  15. return
  16. }
  17. err = conn.ReadDefaultConfigFile()
  18. if err != nil{
  19. resp = []byte("1")
  20. fmt.Printf("ConnCephStruct() can not get %s info, %s", param, err )
  21. return
  22. }
  23. err = conn.Connect()
  24. if err != nil{
  25. resp = []byte("1")
  26. fmt.Printf("ConnCephStruct() can not get %s info, %s", param, err )
  27. return
  28. }
  29. resp, _, err = conn.MonCommand([]byte(`{"prefix":"` + param + `", "format":"json-pretty"}`))
  30. if err != nil {
  31. resp = []byte("1")
  32. fmt.Printf("ConnCephStruct() can not get %s info, %s", param, err )
  33. return
  34. }
  35. if err != nil {
  36. resp = []byte("1")
  37. fmt.Printf("ConnCephStruct() can not get %s info, %s", param, err )
  38. return
  39. }
  40. conn.Shutdown()
  41. return
  42. }
  43. func GetCephMasters()( cephMonstat []models.UploadStatus, err error ){
  44. mon_status := "mon_status"
  45. cephInfo, err := ConnCephStruct(mon_status)
  46. if err != nil {
  47. fmt.Printf("GetMonStatus() can not get 'mon_status' info %s " , err)
  48. os.Exit(1)
  49. }
  50. if len(cephInfo) == 1 {
  51. fmt.Printf("GetMonStatus() can not get 'mon_status' ")
  52. os.Exit(1)
  53. }
  54. var cephMonDetail models.CephMonStruct
  55. err = json.Unmarshal( cephInfo, &cephMonDetail) <- ceph 命令数据存放至 cephMonDetail 结构中
  56. cephMons := cephMonDetail.Monmap.Mons <- 只取 Mons 中的返回数据
  57. for _, i := range cephMons {
  58. var cephStatus models.UploadStatus <- 数据重新定义到 cephStatus
  59. var monStatus models.MonStatus
  60. cephStatus.Rank = i.Rank
  61. monStatus.IpAddr = i.Addr
  62. monStatus.HostName = i.Name
  63. cephStatus.Mons = monStatus
  64. cephMonstat = append(cephMonstat, cephStatus)
  65. }
  66. return
  67. }

当前函数 cephStatus() 将会返回下面效果

  1. [{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}}]

上传方法

  1. [root@ns-yun-020049 src]# cat client/curlpost.go
  2. package client
  3. import (
  4. "fmt"
  5. "net/http"
  6. "io/ioutil"
  7. "encoding/json"
  8. "bytes"
  9. )
  10. func SendListData(s interface{}, serverUrl string) (result []byte) {
  11. b, _ := json.Marshal(s)
  12. body := bytes.NewBuffer([]byte(b))
  13. res, err := http.Post(serverUrl, "application/json;charset=utf-8", body)
  14. if err != nil {
  15. fmt.Println("post err:", err)
  16. return
  17. }
  18. result, err = ioutil.ReadAll(res.Body)
  19. res.Body.Close()
  20. if err != nil {
  21. fmt.Println("post err:", err)
  22. return
  23. }
  24. return
  25. }

注意

  1. 当前上传的数据为 python list 结构, 因此定义了参数传入定义为 interface{} 类型
  2. 假如上传的数据为 python dict 结构, 需要定义参数传入定义为 map[string]interface{} 类型
  3. 定义另外一个函数即可
  4. func SenDictdData(s map[string]interface{}, serverUrl string) (result []byte) {

主函数上传数据方法

  1. package main
  2. import (
  3. "fmt"
  4. _ "reflect"
  5. "client"
  6. )
  7. func main(){
  8. var postData interface{}
  9. url := "http://10.199.210.114/upload/"
  10. postData, _ = client.GetCephMasters()
  11. postInfo := client.SendListData(postData, url)
  12. fmt.Println(string(postInfo))
  13. }

参考 django 获得数据如下:

  1. <type 'list'>
  2. [{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. 1. 数据类型为 python list 结构
  2. 2. 直接使用了 models/uploadstruct.go 中的 UploadStatus 结构体
  3. 3. 直接使用结构体中的 json 定义了数据

发表评论

表情:
评论列表 (有 0 条评论,314人围观)

还没有评论,来说两句吧...

相关阅读

    相关 GoLang—爬虫—解析JSON数据

    SON作为一种重要的数据格式,具有良好的可读性以及自描述性,广泛地应用在各种数据传输场景中。在网络爬虫中,当网页采用AJAX方式渲染数据时,我们必须找出AJAX的异步请求...

    相关 POSTJSON数据

     POST上传JSON数据到服务器时有以下两种方式,但是最常用的是第二种: 第一种:将要上传的JSON字符串(内容中的双引号前面必须要加转义字符\\)然后按照UTF8编码格式