dictionary - 如何将 POST 正文绑定(bind)到 map ?

标签 dictionary go post struct go-gin

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

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 请求正文中存在的内容和不存在的内容构建一个大型动态 UPDATE SQL。由于 ShouldBind() 绑定(bind)到一个结构,因此我无法在不使用反射的情况下迭代主体中的值。我认为一种更简单的方法是查看是否有一种方法可以将请求绑定(bind)到 map 而不是结构。有上下文方法 PostFormMap(key string),但是据我从此处给出的示例 (https://github.com/gin-gonic/gin#another-example-query--post-form) 可以看出,此方法需要与请求中的参数键相对应的值 body 。有没有人有这样做的经验?谢谢!

最佳答案

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

https://play.golang.org/p/ydLuLsY8qla

关于dictionary - 如何将 POST 正文绑定(bind)到 map ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57977531/

相关文章:

Gorilla session.AddFlash 不添加 Flash 消息

java - 将 JSON 发布到后端

arrays - 为什么按索引访问此 json 子元素会引发此错误?

go - 打开 _rels/.rels : permission denied golang

python - 函数字典的语法?

mongodb - Golang Mongodb Bson字符串 slice 数组解码错误

css - Wordpress:帖子文本中关于尺寸图像的边距

java - 使用带有多部分的 Volley Post 请求以阿拉伯语发送发布数据

python - 从列表 Python 中向字典添加键

python - 根据值有效地跟踪字典的前 k 个键