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