【问题标题】:How can you bind a POST body to map?如何将 POST 正文绑定到地图?
【发布时间】:2020-11-17 02:37:14
【问题描述】:

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

【问题讨论】:

  • 你试过传入地图吗?在我看来,杜松子酒的 json 绑定正在使用 std lib 的 json 解码器,它接受地图。如果你尝试过但失败了,你能添加你得到的错误吗?
  • @mkopriva 这行得通!谢谢。我以前没有见过在地图上工作的函数示例。

标签: dictionary go post struct go-gin


【解决方案1】:
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

【讨论】:

  • 感谢您的示例! Gin 的绑定功能也完全有效。我没有意识到 Unmarshal 会为地图工作。我确实必须使用map[string]interface{},因为我在请求中有整数,但我可以根据需要断言它们的类型。
猜你喜欢
  • 2012-12-24
  • 2021-07-10
  • 1970-01-01
  • 1970-01-01
  • 2011-03-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多