1
votes

I've been using Gin's ShouldBind() method to bind form data to a struct:

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")

}

But now I need to build a large, dynamic UPDATE SQL based on what is and isn't present in the body of a POST request. Since ShouldBind() binds to a struct I can't iterate over the values in the body without using reflection. I figured an easier way would be to see if there's a method to bind the requests to a map instead of a struct. There is the context method PostFormMap(key string), however as far as I can tell from the example given here (https://github.com/gin-gonic/gin#another-example-query--post-form), this method requires the values correspond to to the argument key in the request body. Does anyone have any experience doing this? Thank you!

1
Have you tried passing in a map? It seems to me that gin's json binding is using the std lib's json decoder, which accepts maps. If you did try but it failed, can you add the error you've got back?mkopriva
@mkopriva This works! Thanks. I hadn't seen an example of the function working on a map before.Richard Miller

1 Answers

3
votes
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