dongyin4202 2016-04-23 05:08
浏览 551

将GO map转换为struct

I was wondering if there is anyway to convert a map into a struct in GO. I came across the package called map structure. However, when i run it, my struct is not getting the values for my map.I have posted relevant bits of my code below

package main

import (
    "encoding/json"
    "fmt"
    "log"
    "net/http"
    "strconv"

    "github.com/drone/routes"
    "github.com/mitchellh/mapstructure"
)

var Infos = []Info{}

type Info struct {
    Keyy   int    `json:"key"`
    Valuee string `json:"value"`
}

var m map[int]string
var outgoingJSON string
var x map[string]string

func main() {
    m = make(map[int]string)
    x = make(map[string]string)
    mux := routes.New()
    mux.Put("/:key1/:value1", PutData)

    mux.Get("/profile", GetProfile)
    http.Handle("/", mux)
    http.ListenAndServe(":3000", nil)
}
func PutData(w http.ResponseWriter, r *http.Request) {

    key_data := r.URL.Query().Get(":key1")
    value_data := r.URL.Query().Get(":value1")
    key2, err := strconv.Atoi(key_data)
    if err != nil {
        panic(err)
    } else {
        m[key2] = value_data
    }

    for key2, value_data := range m {
        log.Println(key2, value_data)
        log.Println(m)
        x[strconv.FormatInt(int64(key2), 10)] = value_data
        log.Println(x)
        var result Info
        err1 := mapstructure.Decode(x, &result)
        if err1 != nil {
            panic(err1)
        }
        Infos = append(Infos, result)
        //log.Println(key2,value_data)
        //  outgoingJSON, err := json.MarshalIndent(x,"","    ")
        //  if err != nil {
        //  panic(err)
        //    break
        //  }

    }
    w.WriteHeader(204)

    //log.Println(key_data)
}
func GetProfile(w http.ResponseWriter, r *http.Request) {
    w.Header().Set("Content-Type", "application/json")

    for _, p := range Infos {

        outgoingJSON, err := json.MarshalIndent(p, "", "    ")
        if err != nil {
            panic(err)
            break
        }
        w.WriteHeader(200)
        fmt.Fprint(w, string(outgoingJSON))
    }
}

I have create a map[int]string first, converted it into map[string]string and then converted it into my struct. Please help. My struct returns 0 as key and null string as value.

Output:

{
    "key": "",
    "value": ""
}{
    "key": "",
    "value": ""
  • 写回答

1条回答 默认 最新

  • dqiatvbi61502 2016-04-23 07:33
    关注

    MapStructure populates a struct with fields the same name as the keys of the map. Your example generates zero values ( {Key: 0, Value: ""} because there are no keys in the map x with names Key and Value.

    Will the following do what you want?

    package main
    
    import (
        "encoding/json"
        "fmt"
        "net/http"
        "strconv"
    
        "github.com/drone/routes"
    )
    
    // Infos is a slice of Info
    var Infos = []Info{}
    
    // Info is a Key, Value struct
    type Info struct {
        Key   int    `json:"key"`
        Value string `json:"value"`
    }
    
    func main() {
        mux := routes.New()
        mux.Put("/:key1/:value1", PutData)
    
        mux.Get("/profile", GetProfile)
        http.Handle("/", mux)
        http.ListenAndServe(":3000", nil)
    }
    
    // PutData puts the new key,values in to Infos
    func PutData(w http.ResponseWriter, r *http.Request) {
    
        keyData := r.URL.Query().Get(":key1")
        valueData := r.URL.Query().Get(":value1")
        key2, err := strconv.Atoi(keyData)
        if err != nil {
            panic(err)
        } else {
            Infos = append(Infos, Info{
                Key:   key2,
                Value: valueData,
            })
        }
    
        w.WriteHeader(204)
    
    }
    
    // GetProfile displays the Infos
    func GetProfile(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("Content-Type", "application/json")
    
        for _, p := range Infos {
    
            outgoingJSON, err := json.MarshalIndent(p, "", "    ")
            if err != nil {
                panic(err)
                break
            }
            w.WriteHeader(200)
            fmt.Fprint(w, string(outgoingJSON))
        }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥35 引用csv数据文件(4列1800行),通过高斯-赛德尔法拟合曲线,在选取(每五十点取1点)数据,求该数据点的曲率中心。
  • ¥20 程序只发送0X01,串口助手显示不正确,配置看了没有问题115200-8-1-no,如何解决?
  • ¥15 Google speech command 数据集获取
  • ¥15 vue3+element-plus页面崩溃
  • ¥15 像这种代码要怎么跑起来?
  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection
  • ¥15 nginx代理报502的错误
  • ¥100 当AWR1843发送完设置的固定帧后,如何使其再发送第一次的帧