Go语言 gin framework可以获取json post数据,比如'map[string]interface{}',而不是绑定struct吗?

7cjasjjr  于 2023-03-10  发布在  Go
关注(0)|答案(2)|浏览(80)

正如标题所述,我正在编写一个API,获取客户端发布的任何json数据。
有没有办法直接得到bson.M这样的map[string]interface{}类型的数据?
我试着简单地查找gin.Context的属性,如果我错过了什么,它们中的任何一个都能帮助我吗?

nhaq1z21

nhaq1z211#

1.直接从请求主体获取[]bytes
1.使用json.Unmarshal()[]bytes转换为类似JSON的数据:map[string]interface{}

func GetJsonData(c *gin.Context) {
    data, _ := ioutil.ReadAll(c.Request.Body)
    fmt.Println(string(data))

    var jsonData bson.M  // map[string]interface{}
    data, _ := ioutil.ReadAll(c.Request.Body)
    if e := json.Unmarshal(data, &jsonData); e != nil {
        c.JSON(http.StatusBadRequest, gin.H{"msg": e.Error()})
        return
    }
    c.JSON(http.StatusOK, jsonData)
}
eit6fx6z

eit6fx6z2#

你可以使用json解码器

type jsonPrametersMap map[string]interface{}
    var m jsonPrametersMap

    decoder := json.NewDecoder(bytes.NewReader(c.Request.Body))

    if err := decoder.Decode(&m); err != nil {
        fmt.Println(err)
        return
    }

Playground

相关问题