Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/http/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Dictionary 如何将帖子正文绑定到地图?_Dictionary_Go_Post_Struct_Go Gin - Fatal编程技术网

Dictionary 如何将帖子正文绑定到地图?

Dictionary 如何将帖子正文绑定到地图?,dictionary,go,post,struct,go-gin,Dictionary,Go,Post,Struct,Go Gin,我一直在使用Gin的ShouldBind()方法将表单数据绑定到结构: type UpdateUserInfoContext struct { Country string `json:"country"` EmailAddr string `json:"emailAddr"` LoginID string `json:"loginID"` UserName string `json:"username"` } func (h *handler) up

我一直在使用Gin的ShouldBind()方法将表单数据绑定到结构:

type UpdateUserInfoContext struct {
    Country   string `json:"country"`
    EmailAddr string `json:"emailAddr"`
    LoginID   string `json:"loginID"`
    UserName  string `json:"username"`
}

func (h *handler) updateUserInfo(ctx *gin.Context) {

    var json UpdateUserInfoContext

    if err := ctx.ShouldBind(&json); err != nil {
        ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        return
    }

    h.service.UpdateUserPassword(json)

    ctx.JSON(http.StatusOK, "success")

}
但是现在我需要基于POST请求主体中存在和不存在的内容构建一个大型动态更新SQL。由于ShouldBind()绑定到一个结构,我不能在不使用反射的情况下迭代主体中的值。我想一个更简单的方法是看看是否有一种方法可以将请求绑定到映射而不是结构。有一个上下文方法
PostFormMap(key string)
,但是从这里给出的示例()可以看出,这个方法需要与请求主体中的参数key对应的值。有人有这样做的经验吗?谢谢大家!

package main

import (
    "fmt"
    "encoding/json"
)

func main() {

    strbody:=[]byte("{\"mic\":\"check\"}")

    mapbody:=make(map[string]string)

    json.Unmarshal(strbody,&mapbody)

    fmt.Println(fmt.Sprint("Is this thing on? ", mapbody["mic"]))

}    
//returns Is this thing on? check

你试过通过地图吗?在我看来,gin的json绑定使用std-lib的json解码器,它接受映射。如果您确实尝试了,但失败了,您可以添加您返回的错误吗?@mkopriva这很有效!谢谢我以前从未见过在地图上使用该函数的示例。谢谢您的示例!金氏绑定功能也完全有效。我不知道解组器对地图有用。我确实必须使用
map[string]接口{}
,因为我在请求中有int,但是我可以根据需要断言它们的类型。